vue2如何實(shí)現(xiàn)vue3的teleport
vue2實(shí)現(xiàn)vue3的teleport
不支持同一目標(biāo)上使用多個(gè)teleport(代碼通過v-if就能實(shí)現(xiàn))
組件
<script>
?? ?export default {
?? ??? ?name: 'teleport',
?? ??? ?props: {
?? ??? ??? ?/* 移動(dòng)至哪個(gè)標(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逡苿?dòng)到 DOM 中 Vue app 之外的其他位置的技術(shù)。
如果我們嵌套在 Vue 的某個(gè)組件內(nèi)部,那么處理嵌套組件的定位、z-index 和樣式就會(huì)變得很困難。
使用Teleport 就可以方便的解決組件間 css 層級(jí)問題
teleport怎么使用
要使用teleport,首先要在頁面上添加一個(gè)元素,我們要將模態(tài)內(nèi)容移動(dòng)到該頁面
下面舉個(gè)例子
// 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 組件中,還需要指定一個(gè) to 屬性,為該屬性分配一個(gè)查詢選擇器,以標(biāo)識(shí)目標(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)元素中
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3集成Element-plus實(shí)現(xiàn)按需自動(dòng)引入組件的方法總結(jié)
vue3出來一段時(shí)間了,element也更新了版本去兼容vue3,下面這篇文章主要給大家介紹了關(guān)于vue3集成Element-plus實(shí)現(xiàn)按需自動(dòng)引入組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
Vue3封裝自動(dòng)滾動(dòng)列表指令(含網(wǎng)頁縮放滾動(dòng)問題)
本文主要介紹了Vue3封裝自動(dòng)滾動(dòng)列表指令(含網(wǎng)頁縮放滾動(dòng)問題),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
使用vue-cli腳手架工具搭建vue-webpack項(xiàng)目
這篇文章主要介紹了使用vue-cli腳手架工具搭建vue-webpack項(xiàng)目,通過幾個(gè)默認(rèn)的步驟幫助你快速的構(gòu)建Vue.js項(xiàng)目。非常具有實(shí)用價(jià)值,需要的朋友可以參考下2019-01-01
使用element-ui +Vue 解決 table 里包含表單驗(yàn)證的問題
這篇文章主要介紹了使用element-ui +Vue 解決 table 里包含表單驗(yàn)證的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Vue項(xiàng)目線上更新無需強(qiáng)制刷新的幾種實(shí)現(xiàn)方案(無感更新)
在 Vue 項(xiàng)目中,當(dāng)發(fā)布新版本后,用戶可能因?yàn)闉g覽器緩存而繼續(xù)使用舊版本,所以本文給大家介紹了Vue 項(xiàng)目線上更新無需強(qiáng)制刷新的幾種實(shí)現(xiàn)方案,并通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下2025-03-03

