1.编写组件
<template>
<div class="box">
<div :class="['box-main ', { active: isShow }]">{{ info }}==={{time}}</div>
</div>
</template>
<script>
export default {
data() {
return {
info: "",
time:'',
isShow: false,
};
},
mounted() {
setTimeout(() => {
this.isShow = true;
}, 2000);
},
methods: {},
};
</script>
<style scoped>
.box {
width: 100%;
height: 100%;
position: relative;
}
.box-main {
width: 150px;
min-height: 50px;
background: #ccc;
text-align: center;
line-height: 50px;
border-radius: 10px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.active {
transition: all 1s;
opacity: 0;
}
</style>
2.利用扩展类,完成组件
import Vue from 'vue'
import Message from './index.vue'
let MessageConstructor = Vue.extend(Message)
let instance
const MessageTip = function (options = {}) {
instance = new MessageConstructor({
data: options
})
document.body.appendChild(instance.$mount().$el) //this.$el拿到组件实际上的dom,把他挂载到body上
setTimeout(() => {
document.body.removeChild(instance.$mount().$el)
}, 3000); //3秒之后自动移除dom组件
}
export default MessageTip
3.方法挂载到vue原型
import MessageTip from '@/components/message/index.js'
Vue.prototype.$MessageTip = MessageTip
4.使用
<template>
<div id="app">
<button @click="showdialog">显示弹框1</button>
<button @click="showdialog2">显示弹框2</button>
<button @click="showdialog3">显示弹框3</button>
</div>
</template>
<script>
export default {
methods:{
showdialog(){
this.$MessageTip({info:'哈哈',time:new Date()})
},
showdialog2(){
this.$MessageTip({info:'哈哈222'})
},
showdialog3(){
this.$MessageTip({info:'哈哈333'})
}
}
}
<script>