有时候在开发中遇到这种需求,需要在某些页面中动态加载一个弹窗,比如未登录的时候,在点击某些地方,需要弹出登录框要求登录。
如果在每个页面都import进去未免太过繁琐,在根页面引入后监听也不咋好的感觉。
因此,可以使用VUE.extend动态挂在组件。以登录框组件为例:
首先,自然是要一个登录组件页面,login.vue,这个按照自己的需求写就行了。
然后,新建login.js,代码如下:
import Vue from "vue";
import login from "./login.vue";
import store from "../../store";
const PopupBox = Vue.extend(login);
let instance;
login.install = function(data) {
instance = new PopupBox({
data
}).$mount();
instance.$store = store;
document.body.appendChild(instance.$el);
Vue.nextTick(() => {
instance.showLogin();
});
};
login.unInstall = function() {
if (instance) {
document.body.removeChild(instance.$el);
instance.$destroy();
instance = null;
}
};
export default login;
之后,在main.js里加入:
import login from &#