为了方便有需要弹窗确认的交互,可传入回调方法,标题,内容。
首先,我们要创建一个js文件,一般是在 components 文件下,我们这里创建名为:messageBox的文件夹,文件夹下面创建个index.js,下面内容为index.js的内容。
import Vue from "vue"
const MessageBoxPlugin = function (params = {
title: '提示',
content: '请传入content内容'
}) {
const MessageBoxComponent = Vue.extend({
render(h) {
return h('div', { class: 'message-mask' }, [
h('div', { class: 'message-box' }, [
h('div', { class: 'message-box-title' }, params.title),
h('div', { class: 'message-box-content' }, [
h('p', params.content),
h('button', { class: 'message-box-btn', on: { click: this.closeMessageBox } }, '确定')
])
])
])
},
methods: {
closeMessageBox() {
if (typeof params.callback === 'function') {
callback();
}
this.$el.remove();
this.$destroy();
},
},
});
const instance = new MessageBoxComponent();
instance.$mount();
document.body.appendChild(instance.$el);
};
export default MessageBoxPlugin;
script层通过import引入到main.js里。
import MessageBox from "@/components/messageBox"
// 然后挂载全局
Vue.prototype.$MessageBox = MessageBox;
在页面直接调用
this.$MessageBox({
title: '提示',
content: '我是提示内容',
callback: () => {}
})
// 可以只传个content,因为title有默认callback可传可不传
注意:样式要自己设置。vue的h函数里有class名,你也可以自己修改。