vue2如何實現(xiàn)vue3的teleport
vue2實現(xiàn)vue3的teleport
不支持同一目標(biāo)上使用多個teleport(代碼通過v-if就能實現(xiàn))
組件
<script> ?? ?export default { ?? ??? ?name: 'teleport', ?? ??? ?props: { ?? ??? ??? ?/* 移動至哪個標(biāo)簽內(nèi),最好使用id */ ?? ??? ??? ?to: { ?? ??? ??? ??? ?type: String, ?? ??? ??? ??? ?required: true ?? ??? ??? ?} ?? ??? ?}, ?? ??? ?mounted() { ?? ??? ??? ?document.querySelector(this.to).appendChild(this.$el) ?? ??? ?}, ?? ??? ?destroyed() { ?? ??? ??? ?document.querySelector(this.to).removeChild(this.$el) ?? ??? ?}, ?? ??? ?render() { ?? ??? ??? ?return <div>{this.$scopedSlots.default()}</div> ?? ??? ?} ?? ?} </script>
使用
<teleport to="#header__left"> ?? ?<div> ?? ??? ?當(dāng)前組件引用{{msg}} ?? ?</div> </teleport>
vue3新特性teleport介紹
teleport是什么
Teleport 是一種能夠?qū)⑽覀兊哪0逡苿拥?DOM 中 Vue app 之外的其他位置的技術(shù)。
如果我們嵌套在 Vue 的某個組件內(nèi)部,那么處理嵌套組件的定位、z-index 和樣式就會變得很困難。
使用Teleport 就可以方便的解決組件間 css 層級問題
teleport怎么使用
要使用teleport,首先要在頁面上添加一個元素,我們要將模態(tài)內(nèi)容移動到該頁面
下面舉個例子
// index.html <body> ? ... ? <div id="app"></div><!--Vue mounting element--> ? <div id="modal-wrapper"> ? ? <!--modal should get moved here--> ? </div> </body>
我們將模態(tài)內(nèi)容包裝在 teleport 組件中,還需要指定一個 to 屬性,為該屬性分配一個查詢選擇器,以標(biāo)識目標(biāo)元素,在本例中為 #modal-wrapper
// App.vue <template> ? <button @click="toggleModalState">Open modal</button> ? <teleport to="#modal-wrapper"> ? ? <modal v-if="modalOpen"> ? ? ? <p>Hello, I'm a modal window.</p> ? ? </modal> ? </teleport> </template>
teleport 中的任何內(nèi)容都將渲染在目標(biāo)元素中
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3集成Element-plus實現(xiàn)按需自動引入組件的方法總結(jié)
vue3出來一段時間了,element也更新了版本去兼容vue3,下面這篇文章主要給大家介紹了關(guān)于vue3集成Element-plus實現(xiàn)按需自動引入組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07Vue3封裝自動滾動列表指令(含網(wǎng)頁縮放滾動問題)
本文主要介紹了Vue3封裝自動滾動列表指令(含網(wǎng)頁縮放滾動問題),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05使用element-ui +Vue 解決 table 里包含表單驗證的問題
這篇文章主要介紹了使用element-ui +Vue 解決 table 里包含表單驗證的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07Vue項目線上更新無需強制刷新的幾種實現(xiàn)方案(無感更新)
在 Vue 項目中,當(dāng)發(fā)布新版本后,用戶可能因為瀏覽器緩存而繼續(xù)使用舊版本,所以本文給大家介紹了Vue 項目線上更新無需強制刷新的幾種實現(xiàn)方案,并通過代碼示例講解的非常詳細,需要的朋友可以參考下2025-03-03