彈窗這類組件的特點是它們在當(dāng)前vue實例例之外獨?立存在映挂,通常掛載于body;它們是通過JS動態(tài)創(chuàng)建 的空扎,不需要在任何組件中聲明黍匾。常?使用姿勢
this.$create(Notice, {
title: '我是一個彈窗哦',
message: '提示信息',
duration: 1000
}).show();
create
create函數(shù)?用于動態(tài)創(chuàng)建指定組件實例例并掛載?至body
// 創(chuàng)建指定組件實例并掛載于body上
import Vue from 'vue';
export default function create(Component, props) {
// 1.組件實例怎么創(chuàng)建软吐?
// 方式1:借雞生蛋new Vue({render() {}}),在render中把Component作為根組件
// 0. 先創(chuàng)建vue實例
const vm = new Vue({
render(h) {
// render方法提供給我們一個h函數(shù)旭贬,它可以渲染VNode
return h(Component, {props})
}
}).$mount(); // 更新操作
// 1. 上面vm幫我們創(chuàng)建組件實例
// 2. 通過$children獲取該組件實例
const comp = vm.$children[0];
// 3. 追加至body
document.body.appendChild(vm.$el);
// 4. 清理函數(shù)
comp.remove = () => {
document.body.removeChild(vm.$el);
vm.$destroy();
}
// 方式2:組件配置對象 =》 Ctor = Vue.extend(Component)變成構(gòu)造函數(shù)
// =》 new Ctor()
const Ctor = Vue.extend(Component)
1. 創(chuàng)建組件實例
const comp = new Ctor({
popsData: props
})
// 2.獲取該組件實例
comp.$mount()
// 3. 追加至body
document.body.appendChild(comp.$el)
// 4. 清理函數(shù)
comp.remove = () => {
document.body.removeChild(comp.$el);
comp.$destroy();
}
// 5. 返回組件實例
return comp;
}
創(chuàng)建通知組件怔接,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();