在element ui vue2版本的组件库中,发现了一个可以通过this.$notify直接调用的提示组件,不需要import引入就可以,在多方资料查找和阅读下终于理清了他的实现方式
实现步骤
1、通过Vue.extend()构造一个组件实例
2、挂载渲染 Vue.extend()的实例
3、抛出 Vue.extend() 实例
4、在main.js文件中导入,挂载在vue的prototype上
5、在页面中引用
main.js
import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue'
import notice from './components/notice/index.js'
Vue.use(ElementUI);
Vue.config.productionTip = false
Vue.prototype.bus = new Vue()
Vue.prototype.$notice = notice;//挂载组件
new Vue({
render: h => h(App),
}).$mount('#app')
组件目录的结构
组件的写法
import Vue from 'vue'
import notice from './notice.vue'
const constructor = Vue.extend(notice); //相当于一个构造器
export default function showNotice(option){
const instance = new constructor({
data:{
...option //调用是传递过来的值会覆盖合并组件里的data
}
})
instance.$mount();//渲染组件
document.body.append(instance.$el);// 挂载到body上 ,$el是组件template的标签
return instance
}
<template>
<div class="tipBox" v-if="show">
<h4>{{title}}</h4>
<div>{{message}}</div>
<i class="el-icon-close icon" @click="close"></i>
</div>
</template>
<script>
export default{
data() {
return{
title:'',
message:'',
duration:3000,
show:true
}
},
created() {
setTimeout(()=>{
this.close();
},this.duration)
},
methods:{
close(){
this.show = false
}
}
}
</script>
<style>
.tipBox{
width: 40%;
height:140px;
position: fixed;
top: 50%;
left:50%;
transform: translateX(-50%) translateY(-50%);
border:1px solid #ccc;
border-radius: 10px;
box-sizing: border-box;
padding: 20px;
box-shadow: 2px 0px 8px #eee;
}
.tipBox .icon{
position: absolute;
right: 20px;
top: 20px;
}
</style>
使用方法
openCoustom(){
this.$notice({
title:"12023",
message:"学习的咋么样?",
duration:500
})
}