首先先创建一个Notice.vue组件
Notice.vue
<template> <div class="box" v-if="isShow"> <div>{{title}}</div> <div>{{content}}</div> </div></template><script>export default { props: { title: { type: String, default: "", }, content: { type: String, default: "", }, duration: { type: Number, default: 1000, }, }, data() { return { isShow: false, }; }, methods: { show() { this.isShow = true; setTimeout(this.hide, this.duration); }, hide() { this.isShow = false; this.remove(); }, },};</script><style lang="" scoped>.box { position: fixed; width: 100%; top: 16px; left: 0; text-align: center; pointer-events: none; background: #fff; border: 2px solid #d9d9d9;}</style>
这一部分不多赘述,页面样式根据自己的需要就好
--------
create.js 第一种
import Vue from "vue";
// Component - 组件配置对象 (模具)// props - 传递给它的属性
const create = function (Components,props){ // 构建实例
const vm = new Vue({
render(h){
return h(Components,{props})
}
}).$mount()
// 挂载
document.body.appendChild(vm.$el)
// 获取组件实例
const comp = vm.$children[0]
// 结束后销毁
comp.remove = () =>{
document.body.removeChild(vm.$el)
vm.$destroy()
}
return comp;
}
export default create;
import Vue from "vue";
// Component - 组件配置对象 (模具)// props - 传递给它的属性
const create = function (Components,props){ // 构建实例
const vm = new Vue({
render(h){
return h(Components,{props})
}
}).$mount()
// 挂载
document.body.appendChild(vm.$el)
// 获取组件实例
const comp = vm.$children[0]
// 结束后销毁
comp.remove = () =>{
document.body.removeChild(vm.$el)
vm.$destroy()
}
return comp;
}
export default create
index.js 引用
import Notice from "@/components/Notcie"
import create from "@/utils/create"
//...
methods:{
***(){
create(Notice,{title:"",message:""});
}
}
第二种,
create.js
import Vue from "vue";import Notice from "@/components/Notice.vue"
const create = function (Components,props){
var Ctor = Vue.extend(Component)
const comp = new Ctor({propsData:props})
comp.$mount()
document.body.appendChild(comp.$el);
comp.remove = () =>{
document.body.removeChild(comp.$el)
comp.$destroy()
}
return comp;
}
export default create;
在index.js 中引用方法不变
第三种
create.js
import Vue from "vue";import Notice from "@/components/Notice.vue"const create = function (Component, props) { var Ctor = Vue.extend(Component) const comp = new Ctor({ propsData: props }) comp.$mount(); document.body.appendChild(comp.$el); comp.remove = () => { document.body.removeChild(comp.$el); comp.$destroy(); } return comp}export default { install(Vue) { Vue.prototype.$notice = function (options) { const comp = create(Notice, options) comp.show() return comp } }};
main.js 全局引用
import create from './utils/create'Vue.use(create)
index.js 中
直接使用 this.$notice({title:"",message:""})
即可