Vue3传送门Teleport示例

teleport

teleport可以让我们的子组件DOM不用嵌套在父组件的DOM中,但又可以继续访问父组件的值和方法

子组件,用teleport包裹,这里的to对应的是App.vue里面的id

<template>
  <teleport to="#title">
    <div class="box">
      <slot>标题</slot>
    </div>
    <div class="placehoder"></div>
  </teleport>
</template>
<script>
export default {
     
     };
</script>
<style lang='less' scoped>
.box {
     
     
  width: 100%;
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  background: #fff;
  z-index: 1;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 25px;
}

.placehoder {
     
     
  width: 100%;
  height: 50px;
}
</style>

App.vue

 <div id="app"></div>
 <div id="title"></div>

父组件进行引入

<template>
  <div>
    <navbar>{
   
   { title }}</navbar>
  </div>
</template>

<script>
import {
     
      reactive, toRefs } from "vue";
import navbar from "../../components/navbar";
export default {
     
     
  components: {
     
     
    navbar,
  },
  setup() {
     
     
    const that = reactive({
     
     
      title: "main页",
    });
    return {
     
     
      ...toRefs(that),
    };
  },
};
</script>

可以看到浏览器渲染出来的是父子组件DOM分离的
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AK852369/article/details/115022375