目录结构:
mAlert.vue的代码:
<template>
<div id="mAlert" v-show="showAlert">
<div class="box">
<p>{{config.txt}}</p>
<div>
<span @click="ok()">{{config.okTxt || '确定'}}</span>
<span @click="no()">{{config.noTxt || '取消'}}</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: "mAlert.vue",
props: {
config: {
type: Object,
default: function () {
return {
txt: '',
okTxt: '确定',
noTxt: '取消'
}
}
}
},
data () {
return {
showAlert: false
}
},
}
</script>
<style scoped>
#mAlert{
position: fixed;
z-index: 999;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.7);
}
.box{
width: 61.8%;
border-radius: 10px;
background: #fff;
text-align: center;
margin: 30% auto 0;
}
.box p{
padding: 20px;
}
.box div{
display: flex;
border-top: 1px solid #ccc;
}
.box span{
flex: 1;
padding: 10px;
}
.box span:first-child{
border-right: 1px solid #ccc;
color: dodgerblue;
}
</style>
mAlert.js的代码:
import mAlertDom from './mAlert.vue'
import Vue from 'vue'
let mAlert = {}
mAlert.install = function (Vue, options) {
const constructor = Vue.extend(mAlertDom)
const instance = new constructor()
Vue.prototype.$mAlert = (config) => {
return new Promise((resolve, reject) => {
instance.config = config
instance.showAlert = true
instance.no = () => {
instance.showAlert = false
reject(false)
}
instance.ok = () => {
instance.showAlert = false
resolve(true)
}
})
}
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
}
export default mAlert
main.js引入并use:
import mAlert from "./plugin/mAlert/mAlert.js"
Vue.use(mAlert)
调用:
this.$mAlert({txt: '又在写bug?'}).then((res) => {
console.log(res) // 点击了确定按钮
}).catch((err) => {
console.log(err) // 点击了取消按钮
})