1.创建消息模板
<template>
<div class="wrap">一条消息</div>
</template>
<style scoped>
.wrap {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: rgba(12, 12, 12, 0.212);
padding: 10px;
border-radius: 5px;
color: #fff;
}
</style>
2.利用 vue.extend 生产 vue构造器
import vue from 'vue'
import showMsg from './showMsg.vue'
const MsgConstructor = vue.extend(showMsg)
function showMsgs(text, duration = 2000) {
const msgDom = new MsgConstructor({
el: document.createElement('div'),
data() {
return {
text: text,
show: true
}
}
})
document.body.appendChild(msgDom.$el)
setTimeout(() => {
msgDom.show = false
}, duration)
}
function registryMsg() {
vue.prototype.$msg = showMsgs
}
export default registryMsg
3.使用
Vue.use(registryMsg)
msg() {
this.$msg('hahahhaa')
}