封装组件是为了能够更加便捷、快速的进行业务功能的开发。组件可以实现一些类似功能的复用及与其它业务逻辑的解耦。在开发中,我们难免会写很多类似的、重复的代码,有些相似的功能但涉及的字段有一些不一样。这时候可以把那些相同的功能,抽出来封装成组件,通过组件引用方式就很省事了。
今天我们来封装一个使用率非常频繁的一个组件 弹窗
全局dialog封装 这里用的createVNode,render
第一步,在components文件夹中创建一个dialog.vue 文件
<script setup>
const props = defineProps({
title: {
type: String,
default: '提示'
},
content: {
type: String,
default: ''
},
className: {
type: String,
default: 'text-center'
},
cancelButtonText: {
type: String,
default: '取消'
},
okButtonText: {
type: String,
default: '确定'
},
okButton: {
type: Function
},
cancelButton: {
type: Function
}
})
</script>
<template>
<!--dialog-modal-->
<view class="dialog-modal show">
<view class="flex">
<view class="box">
<view class="modal-title">
{{ title }}
</view>
<view :class="`${className} modal-desc`">
<text class="text">{{ content }}</text>
</view>
<view class="modal-btn">
<button class="btn" @click='cancelButton'>{{ cancelButtonText }}</button>
<button class="confirm btn" @click='okButton'>{{ okButtonText }}</button>
</view>
</view>
</view>
</view>
</template>
<style lang="less" scoped>
.dialog-modal {
position: fixed;
background-color: rgba(0, 0, 0, 0.5);
left: 0;
top: 0;
width: 100%;
height: 100%;
display: none;
.flex {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
.box {
background-color: #ffffff;
border-radius: 20rpx;
padding: 40rpx;
width: 65%;
text-align: center;
font-size: 28rpx;
.modal-title {
font-size: 32rpx;
font-weight: bold;
color: var(--zpyj-text-main-color);
}
.modal-desc {
margin: 30rpx 0;
.text {
display: block;
line-height: 44rpx;
}
&.text-left {
text-align: left;
}
&.text-center {
text-align: center;
}
}
.modal-btn {
display: flex;
align-items: center;
justify-content: space-between;
.btn {
background-color: #f6f6f6;
border-radius: 44rpx;
padding: 0 70rpx;
font-size: 32rpx;
margin: 0;
&.confirm {
background-image: linear-gradient(90deg, var(--zpyj-text-main-color) 0%, #4993ff 100%);
color: #fff;
}
}
}
}
}
&.show {
display: block;
}
}
</style>
import { createVNode, render } from 'vue'
import Dialog from './uDialogModal.vue'
const divDom = document.createElement('div')
divDom.setAttribute('class', 'u-dialog-modal-container')
document.body.appendChild(divDom);
const dialogPlguin = (option) => {
return new Promise((resolve, reject) => {
const okButton = () => {//确认
render(null, divDom)
resolve()
}
const cancelButton = () => {// 取消
render(null, divDom)
reject(new Error('取消'))
}
const vNode = createVNode(Dialog, { ...option, okButton, cancelButton })
render(vNode, divDom)
})
}
export default dialogPlguin
//第二种方式
// export default {
// install(app) {
// app.config.globalProperties.$dialog = dialogPlguin
// }
//main.js中引入
//import dialog from './utils/dialog'
//app.use(dialog).mount('#app')
// }