## :-: Vue 全局挂载组件的通用方法 :-: @/plugins/create.js ``` import Vue from 'vue' /* * Vue 全局挂载组件的通用方法 * create(Component, props, callBack); */ export default function create(Component, props, callBack) { // 创建实例 const vm = new Vue({ render(h) { // h为createElement,返回VNode虚拟Node return h(Component, { props }); } }).$mount(); // 手动挂载实例到body document.body.appendChild(vm.$el); const comp = vm.$children[0]; // 销毁方法 comp.$remove = function (data) { document.body.removeChild(vm.$el); vm.$destroy(); typeof callBack === 'function' && callBack('close', data); } // 返回组件 return comp; } ``` :-: @/main.js ``` import create from "@/plugins/create.js" Vue.prototype.$create = create; // Vue全局挂载组件的通用方法、 ``` :-: @/components/E-alert.js ``` // 提供一个退出的方法 (其他的跟普通组件一样) methods: { close(data) { // 调用销毁组件的方法 (自动判断是静态/动态调用,进行不同的处理) this.$remove ? this.$remove(data) : this.$emit("close", data); } } ``` :-: @/App.vue ``` import EAlert from "@/components/E-alert.vue"; export default { mounted() { this.$create( EAlert, { title: "温馨提示", content: "该Object会当做props传入组件" }, (type, data) => { /* * '动态'组件的调用函数 * type -- 类型(如close为销毁时触发的)、 * data -- '动态'组件返回的数据。 */ console.log(data); } ); } } ```