弹窗这类组件的特点是它们在当前vue实例例之外独⽴立存在,通常挂载于body;它们是通过JS动态创建 的,不需要在任何组件中声明。常⻅使用姿势
this.$create(Notice, {
title: '我是一个弹窗哦',
message: '提示信息',
duration: 1000
}).show();
create
create函数⽤用于动态创建指定组件实例例并挂载⾄至body
// 创建指定组件实例并挂载于body上
import Vue from 'vue';
export default function create(Component, props) {
// 1.组件实例怎么创建?
// 方式1:借鸡生蛋new Vue({render() {}}),在render中把Component作为根组件
// 0. 先创建vue实例
const vm = new Vue({
render(h) {
// render方法提供给我们一个h函数,它可以渲染VNode
return h(Component, {props})
}
}).$mount(); // 更新操作
// 1. 上面vm帮我们创建组件实例
// 2. 通过$children获取该组件实例
const comp = vm.$children[0];
// 3. 追加至body
document.body.appendChild(vm.$el);
// 4. 清理函数
comp.remove = () => {
document.body.removeChild(vm.$el);
vm.$destroy();
}
// 方式2:组件配置对象 =》 Ctor = Vue.extend(Component)变成构造函数
// =》 new Ctor()
const Ctor = Vue.extend(Component)
1. 创建组件实例
const comp = new Ctor({
popsData: props
})
// 2.获取该组件实例
comp.$mount()
// 3. 追加至body
document.body.appendChild(comp.$el)
// 4. 清理函数
comp.remove = () => {
document.body.removeChild(comp.$el);
comp.$destroy();
}
// 5. 返回组件实例
return comp;
}
创建通知组件,Notice.vue
<template>
<div v-if="isShow">
<h3>{{title}}</h3>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: ""
},
message: {
type: String,
default: ""
},
duration: {
type: Number,
default: ""
}
},
data() {
return {
isShow: false
};
},
methods: {
show() {
this.isShow = true;
setTimeout(() => {
this.hide()
}, this.duration);
},
hide() {
this.isShow = false;
this.remove();
}
}
};
</script>
<style lang="scss" scoped>
</style>
使⽤
import Notice from "../Notice";
import create from "@/utils/create";
const notice = create(Notice, {
title: "我是一个弹窗哦",
message: "提示信息",
duration: 1000
});
notice.show();