vue3動態建立元件,掛載到dom 節點上,修復版本
阿新 • • 發佈:2020-12-19
// 將元件掛在到節點上! const creatComp = (comp:Component,prop:Object)=>{ var app = createApp(comp,{ ...prop }) var divEle = document.createElement("div") // 讓我們節點掛在到一個dom元素上 document.body.appendChild(divEle) app.mount(divEle) // 解除繫結的時候 onUnmounted(()=>{ app.unmount(divEle) document.body.removeChild(divEle) }) }
使用:
這樣就可以建立任何元件, 並且掛載到dom 節點上了,但是還是無法互動!
這個時候,就要思考, 若是這個動態的元件是自己處理邏輯,就不需要互動,如果需要互動呢,
這個時候,我們就考慮傳遞方法進去? 或者用 emit ??
這個我們都要考慮,先 實現了再說,然後繼續思考
1,自己處理
<template> <!-- 最終呢,我們的元件就會掛在到#dialog 一個documentElement --> <teleport to ="#dialog" v-if ="show1"> <div class="fixed-top"> <h2>i am a dialog...</h2> <button @click.prevent = "closeTag" class="btn btn-primary">close</button> </div> </teleport> </template> <script lang="ts"> import Vue from 'vue' import {defineComponent,onUnmounted,watch,reactive ,toRefs} from 'vue' export default defineComponent({ name:"dialog", props:{ show:{ default:false, type:Boolean } }, setup(prop,context){ const mountEle = document.createElement("div"); const data = toRefs(reactive({ show1:false })); data.show1.value = prop.show; mountEle.id = "dialog"; // 掛在到body 上 document.body.appendChild(mountEle) onUnmounted(()=>{ // 當元件消亡的時候,我們就清空節點 document.body.removeChild(mountEle) }) const closeTag = ()=>{ data.show1.value = false; } return { ...data, closeTag } } }) </script> <style> </style>
當我們點選關閉按鈕時就自己關閉得了,如果需要互動呢?我們用emit?
這個我沒法用,因為現在是動態建立的,咋接收,我現在不知道!
行,暫時寫到這裡,回頭我們繼續