vue3新特性teleport傳送原來這么神奇


我對teleport的理解

teleport有傳送的意思,讀音【te li po t】[嘻嘻],看官們應該知道讀啥子了吧
它可以將你寫的代碼傳送到某一個地方
傳送到哪一個地方呢?
傳送到你標記的地方,比如說傳送到body下,html下

官方說:Teleport 是一種能夠將我們的模板移動到 DOM 中 Vue app 之外的其他位置的技術,
上面這一句話是說傳送到除了app之外的地方。
也就是說不能夠傳送到app之內。【注意了】
點像哆啦A夢的“任意門”
主要運用在彈窗上,消息提示,這樣的場景!
下面我們就來簡單使用一下:
我們將彈窗組件移動到body下

場景描述

a-test組件中有b-test組件,b-test組件中有c-mask[彈窗組件]
我們點擊按鈕,將b-test組件中的組件c-mask[彈窗組件]移動到body下

容器下有a-test組件

<template>
  <div class="box">
    <a-test></a-test>  
  </div>
</template>

<script>
import atest from '../components/a-test.vue'
  export default {
    components:{
      'a-test':atest,
    },
  }
</script>

a-test組件下有b-test組件

<template>
  <div class="a-test" >
    我是a-test組件
    <b-test></b-test>
    <div id="testdemo"></div>
  </div>
</template>

<script>
import btest from '../components/b-test.vue'
export default {
  components:{
      'b-test':btest
  },
}
</script>

b-test組件下有c-mask[彈窗組件]組件

<template>
  <div class="b-test">
    我是b-test組件
    <c-mask></c-mask>
  </div>
</template>

<script>
import cmask  from "./c-mask.vue"
export default {
  components:{
      'c-mask':cmask
  },
}
</script>

c-mask[彈窗組件]組件移動到body下

<template>
  <div>
    <a-button type="primary" @click="openHander">open</a-button>
    <!-- 將內容區域的代碼移動到body下 -->
    <teleport to='body'>
      <div class="mask" v-if="showFlag">
        <h1>對話框組件</h1>
        <div>
            我是內容哈哈
        </div>
        <a-button  @click="openHander">關閉</a-button>
      </div>
    </teleport>
  </div>
</template>

<script>
import { ref } from '@vue/reactivity'
export default {
    setup () {
        let showFlag=ref(false)
        const openHander=()=>{
            showFlag.value=!showFlag.value
        }
        return {showFlag,openHander}
    }
}
</script>

主要注意的地方

通過上面的小粒子,想必你已經看明白了。
需要注意的是不可以移動到#app之內
我們可以在index.html中創建id=myapp的容器
將它傳送在myapp容器下,我們看一下

index.html 創建一個容器

<body>
    <div id="app"></div>
    //等會將會傳送到這里哈
    <div id="myapp"></div>
  </body>

傳送

<template>
  <div>
    <a-button type="primary" @click="openHander">open</a-button>
    <!-- 將內容區域的代碼移動到id=myapp下 -->
    <teleport to='#myapp'>
        <div class="mask" v-if="showFlag">
            <h1>對話框組件</h1>
            <div>
                我是內容哈哈
            </div>
            <a-button  @click="openHander">關閉</a-button>
        </div>
    </teleport>
  </div>
</template>
<script>
import { ref } from '@vue/reactivity'
export default {
  setup () {
    let showFlag=ref(false)
    const openHander=()=>{
        showFlag.value=!showFlag.value
    }
    return {showFlag,openHander}
  }
}
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM