前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue3 Teleport瞬移组件

vue3 Teleport瞬移组件

作者头像
Qwe7
发布2022-06-30 09:19:32
3830
发布2022-06-30 09:19:32
举报
文章被收录于专栏:网络收集

6、 vue3 Teleport瞬移组件

Teleport一般被翻译成瞬间移动组件,实际上是不好理解的.我把他理解成"独立组件", 将组件的 DOM 元素挂载在任意指定的一个 DOM 元素,与 React Portals 的概念是一致的。

他可以那你写的组件挂载到任何你想挂载的DOM上,所以是很自由很独立的

编写一个例子

// HelloWorld.vue

代码语言:javascript
复制
<template>
  <div>
    <h2>Hello World</h2>
  </div>
</template>

<script>
  export default {
    
  }
</script>

<style scoped>

</style>

在App.vue中使用的时候跟普通组件调用是一样的

// App.vue

代码语言:javascript
复制
<template>
  <div class="app">
    <teleport to="#why">
      <h2>当前计数</h2>
      <button>+1</button>
      <hello-world></hello-world>
    </teleport>

    <teleport to="#why">
      <span>呵呵呵呵</span>
    </teleport>
  </div>
</template>

<script>
  import { getCurrentInstance } from "vue";

  import HelloWorld from './HelloWorld.vue';

  export default {
    components: {
      HelloWorld
    },
    setup() {
      const instance = getCurrentInstance();
      console.log(instance.appContext.config.globalProperties.$name);
    },
    mounted() {
      console.log(this.$name);
    },
    methods: {
      foo() {
        console.log(this.$name);
      }
    }
  }
</script>

<style scoped>

</style>

要是在App.vue文件中使用的时候,hello-world组件是在App的 DOM节点之下的,父节点的dom结构和css都会给hello-world组件产生影响

于是产生的问题

hello-world组件被包裹在其它组件之中,容易被干扰

样式也在其它组件中,容易变得非常混乱

Teleport 可以把hello-world组件渲染到任意你想渲染的外部Dom上,不必嵌套在#app中,这样就可以互不干扰了,可以把Teleport看成一个传送门,把你的组件传送到任何地方

使用的时候 to属性可以确定想要挂载的DOM节点下面

代码语言:javascript
复制

<template>
  <div class="app">
    <teleport to="#why">
      <h2>当前计数</h2>
      <button>+1</button>
      <hello-world></hello-world>
    </teleport>

    <teleport to="#why">
      <span>呵呵呵呵</span>
    </teleport>
  </div>
</template>

在public文件夹下的index.html中增加一个节点

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    
    <div id="why"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档