1. 程式人生 > 其它 >Vue動態建立元件例項並掛載到body

Vue動態建立元件例項並掛載到body

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Vue from 'vue'
 
/**
 * @param Component 元件例項的選項物件
 * @param props 元件例項中的prop
 */
export function create(Component, props) {
 const comp = new (Vue.extend(Component))({ propsData: props }).$mount()
  
 document.body.appendChild(comp.$el)
 
 comp.remove 
= () => { document.body.removeChild(comp.$el) comp.$destroy() } return comp }

 

方式二

import Vue from 'vue'
 
export function create(Component, props) {
 // 借雞生蛋new Vue({render() {}}),在render中把Component作為根元件
 const vm = new Vue({
  // h是createElement函式,它可以返回虛擬dom
  render(h) {
   console.log(h(Component,{ props }));
    
   
// 將Component作為根元件渲染出來 // h(標籤名稱或元件配置物件,傳遞屬性、事件等,孩子元素) return h(Component, { props }) } }).$mount() // 掛載是為了把虛擬dom變成真實dom // 不掛載就沒有真實dom // 手動追加至body // 掛載之後$el可以訪問到真實dom document.body.appendChild(vm.$el) console.log(vm.$children); // 例項 const comp = vm.$children[0] // 淘汰機制 comp.remove = () => {
// 刪除dom document.body.removeChild(vm.$el) // 銷燬元件 vm.$destroy() } // 返回Component元件例項 return comp }