博客地址:https://ainyi.com/83
常见的 Element 组件的 MessageBox 弹窗组件,调用方法:
this.$confirm('xxx')
还可以增加其回调方法:
this.$confirm('这是一条信息').then(() => {
console.log('确定了')
}).catch(() => {
console.log('关闭了')
})
实现方法
首先在 packages 文件夹下新建 confirm 文件夹,往里面新建 src 目录,存放源代码
src 下新建 Confirm.vue 文件写好相关弹窗的 html、js 代码
应用时有相关的回调函数,相应的实现方法就是使用Promise实现
<template>
<div>
...
</div>
</template>
<script>
export default {
name: 'confirm',
data() {
return {
promptMessage: '',
modelOperate: '确认',
confirmVisible: false,
resolve: '', // promise,类型 function
reject: '' // promise,类型 function
}
},
watch: {},
computed: {
showClass() {
return this.confirmVisible ? 'view' : ''
}
},
mounted() {},
created() {},
filters: {},
methods: {
close() {
this.reject() // catch 获取
this.confirmVisible = false
},
confirm() {
this.resolve() // then 获取
this.confirmVisible = false
}
}
}
</script>
在 Confirm.vue 同级目录下新建 main.js
import Main from './Confirm.vue'
import Vue from 'vue'
let ConfirmConstructor = Vue.extend(Main)
let instance, params
const Confirm = function(options) {
return new Promise((resolve, reject) => { // eslint-disable-line
if (typeof options === 'string') {
params = {
promptMessage: options,
resolve: resolve, // 将 resolve、reject 传到组件内调用
reject: reject
}
} else {
params = {
...options,
resolve: resolve,
reject: reject
}
}
showConfirm()
})
}
const showConfirm = () => {
let options = params || {}
instance = new ConfirmConstructor({
data: options
})
instance.$mount() // 挂载
document.body.appendChild(instance.$el)
instance.confirmVisible = true
}
export default Confirm
然后在上级目录(Confirm 文件夹)下新建 index.js 文件导出
import Confirm from './src/main'
export default Confirm
然后再最外层的 index.js 整合
import Confirm from './confirm'
const install = function(Vue, opts = {}) {
Vue.prototype.$confirm = Confirm
}
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
Confirm,
install
}
最后就可以通过文章最顶部的调用方式愉快地玩耍了
博客地址:https://ainyi.com/83