仿写elmentui的this.$confirm()
第一步,新建一个my-extend-test.vue组件
html部分
<div v-if="show">
需要的组件布局及其样式
</div>
js部分
<script>
export default {
components: { },
props: {
messageText: {
type: String,
default: '确定要删除吗?'
},
confirmText: {
type: String,
default: '确定'
},
cancelText: {
type: String,
default: '取消'
}
},
data () {
return {
promiseStatus: null,
show: false
}
},
created () { },
methods: {
// 创建一个promise对象 并返回其回调方法
setPromiseStatus() {
this.show = true
return new Promise((resolve, reject) => {
this.promiseStatus = { resolve, reject }
})
},
// 确定按钮事件
confirm() {
this.show = false
this.promiseStatus.resolve()
},
// 取消按钮的事件
cancel() {
this.show = false
this.promiseStatus.reject()
}
}
}
</script>
第二步,新建一个my-extend.js的js文件,在里面注册刚刚的组件
import Vue from 'vue'
// 注册组件
import message from './my-extend-test.vue'
const VueComponent = Vue.extend(message)
const vm = new VueComponent().$mount()
let init = false
const confirm = function (options) {
// 合并对象 Object.assign(vm, options)
if (!init) {
document.body.appendChild(vm.$el)
init = true
}
// 返回组件中的promise对象回调函数
return vm.setPromiseStatus()
}
export default confirm
第三步,引用指令
1、全局注册
在main.js中引入js文件,挂到原型上
// 引入js文件
import confirm from '/q-components/my-extend.js'
Vue.prototype.$confirm = confirm
// 使用时
this.$confirm({ confirmText: '确定删除' }).then(() => {
console.log('确定')
}).catch(() => {
console.log('取消')
})
2、局部引入
在需要指令的组件中引入js文件
// 引入js文件
import confirm from '/q-components/my-extend.js'
// 使用时
confirm({ confirmText: '确定删除' }).then(() => {
console.log('确定')
}).catch(() => {
console.log('取消')
})