3.组件构造函数

2020-11-26  本文已影响0人  Json766

组件构造函数如何获取

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 Vue from 'vue'
function create(component,props){
  const vm = new Vue({
    //h是createElement,返回VNode,是虚拟dom
    //需要挂载才能变成真实dom
    return:h => h(component,{props})
  }).$mount() //不指定宿主元素,会创建真实dom,但是不会追加
  //$mount()不可以直接指定body,不然直接覆盖了原有的body
  document.body.appendChild(vm.$el) //获取真实dom
  const comp = vm.$children[0];
  //删除
  comp.remove = function(){
    document.body.removeChild(vm.$el)
    vm.destroy()
  }
  return comp
}
export default create

改装插件

import Vue from 'vue'
import Notice from '@/components/Notice.vue'
function create(component,props){
  const vm = new Vue({
    //h是createElement,返回VNode,是虚拟dom
    //需要挂载才能变成真实dom
    return:h => h(component,{props})
  }).$mount() //不指定宿主元素,会创建真实dom,但是不会追加
  //$mount()不可以直接指定body,不然直接覆盖了原有的body
  document.body.appendChild(vm.$el) //获取真实dom
  const comp = vm.$children[0];
  //删除
  comp.remove = function(){
    document.body.removeChild(vm.$el)
    vm.destroy()
  }
  return comp
}
export default {
  install(Vue){
    Vue.prototype.$notice = function(options){
      return create(Notice,options)
    }
  }
}
//main.js
import create from './utils/create'
Vue.use(create)
上一篇 下一篇

猜你喜欢

热点阅读