vue 组件实例创建

方法一:

import Vue from "vue";
// 创建函数接收要创建组件定义
function create ( Component, props ) {
    // 创建一个Vue新实例 
    const vm = new Vue( {
            render ( h ) {
                // render函数将传入组件配置对象转换为虚拟
                dom console.log( h( Component, {
                    props
                } ) );
                return h( Component, {
                    props
                } );
            }
        } )
        .$mount();
    //执行挂载函数,但未指定挂载目标,表示只执行初始化工作 
    // 将生成dom元素追加至
    body 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";
const Ctor = Vue.extend( Component )
const comp = new Ctor( {
    propsData: props
} )
comp.$mount();
document.body.appendChild( comp.$el )
comp.remove = () => {
    // 移除dom document.body.removeChild(comp.$el)
    // 销毁组件 
    comp.$destroy();
}

 插件封装

import Notice from '@/components/Notice.vue'
//... 
export default {
    install ( Vue ) {
        Vue.prototype.$notice = function ( options ) {
            return create( Notice, options )
        }
    }
}

 

posted @ 2022-09-16 11:29  菜的掉渣  阅读(142)  评论(0编辑  收藏  举报