对话框
该组件是个对话框,基于 Vue 、uni-ui 的 【uni-popup】
组件调用方式、优点及需求来源
组件调用方式
this.$tipPop("请输入手机号/邮箱/用户名").then(() => {
// 这里执行 确定后的回调
})
组件优点
使用插件方式引入,不需要在模板中定义
需求来源
一个对话框,使用页面很多,只有提示文件是动态的,但是需要知道用户点击了哪个按钮。每次都在模板中定义很麻烦
代码分析
tipsPop.vue(定义构造器)
<template>
<uni-popup ref="popup" :mask-click="false">
<view class="pop-box w-flex-column w-flex-cross-center">
<uni-icons type="info" size="100" color="#f8cb86"></uni-icons>
<text class="text-center">{{ popTxt }}</text>
</view>
<button type="primary" class="pop-btn" @click="submit">确定</button>
</uni-popup>
</template>
<script setup>
import {
ref,
defineExpose,
onMounted
} from 'vue';
const callback = ref(null);
const popup = ref()
defineProps({
popTxt: String
});
function openPop() {
popup.value.open('center');
}
function submit() {
callback.value();
}
defineExpose({
callback,
openPop
})
</script>
<style scoped>
.pop-box {
width: 190px;
padding: 10px 30px;
background-color: #fff;
border-radius: 6px 6px 0px 0px;
}
.pop-btn {
width: 100%;
background-color: #4cd964;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
</style>
tipsPop.js(使用 extend 方法创建组件实例)
import {
createApp
} from 'vue'
import TipsPop from './tipsPop.vue'
let cApp = null,
mountDom = null,
instance = null
// 创建实例
function initInstance(propsData) {
cApp = createApp(TipsPop, propsData)
mountDom = document.createElement('div')
instance = cApp.mount(mountDom)
}
function mergeOpt({
popTxt
}) {
return {
popTxt
}
}
function showDialog() {
document.body.appendChild(mountDom)
instance.openPop()
}
function unmount() {
cApp.unmount()
mountDom = null
instance = null
}
export default function(tips) {
const propsData = mergeOpt({
popTxt: tips
})
if (!instance) {
initInstance(propsData)
}
showDialog()
return new Promise((resolve, reject) => {
instance.callback = () => {
resolve()
unmount()
}
})
}
install.js(抛出一个install 方法,用户插件注册)
import tips from './tipsPop.js'
export default {
install: (app, options) => {
app.config.globalProperties.$tipPop = tips
}
}