Vue3 Portal Teleport example

teleport

teleportAllows our child components DOMnot to be nested in the parent component DOM, but can continue to access the values ​​and methods of the parent component

Sub-components, wrapped in teleport, here tocorresponds to App.vuethe id inside

<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>

View app

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

The parent component is introduced

<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>

You can see that what the browser renders is separated from the DOM of the parent and child components
Insert picture description here

Guess you like

Origin blog.csdn.net/AK852369/article/details/115022375