vue3新特性teleport传送原来这么神奇!

1,043 阅读2分钟

「这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战

我对teleport的理解

teleport有传送的意思,读音【te li po t[嘻嘻],看官们应该知道读啥子了吧
它可以将你写的代码传送到某一个地方
传送到哪一个地方呢?
传送到你标记的地方,比如说传送到body下,html下

官方说:Teleport 是一种能够将我们的模板移动到 DOMVue 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>