层级问题-teleport传送门

152 阅读1分钟

teleport 传送门 -解决层级嵌套问题

  • 首先我们先创建一个vue3的项目
  • 接下来 复制以下代码
  1. Box1.vue
<template>
  <div style="width: 600px; height: 300px; position: relative; z-index: 3; background: pink;">
    <h1>我是盒子1</h1>
  </div>
</template>

<script>
export default {
  name: 'XtxBox1',

};
</script>

<style lang="scss" scoped>

</style>

  1. Box2.vue
<template>
  <div style="width: 600px; height: 300px; position: relative; z-index: 2; background: skyblue;">
    <h1>我是盒子2</h1>
    <button @click="isShow = true">显示弹框</button>

    <XtxDialog title="警告" :visible="isShow" @close="handleCloseFn">
      <template #default>
        <p>我是内容</p>
        <p>我是内容</p>
        <p>我是内容</p>
        <p>我是内容</p>
      </template>

      <template #footer>
        <XtxButton type="gray" style="margin-right:20px" @click="isShow = false"></XtxButton>
        <XtxButton type="primary"></XtxButton>
      </template>
    </XtxDialog>
  </div>
</template>

<script>
import { ref } from 'vue'
export default {
   name: 'XtxBox2',
  setup () {
    const isShow = ref(false)

    const handleCloseFn = (flag) => {
      isShow.value = false
    }
    return {
      isShow,
      handleCloseFn
    }
  }
}
</script>
<style lang="scss" scoped>

</style>

  1. index.vue
<template>
  <div>
    <Box-1></Box-1>
    <Box-2></Box-2>
    123123
  </div>
</template>
<script>
import Box1 from './components/box1.vue'
import Box2 from './components/box2.vue'
export default {
  name: 'XtxIndex',
components:{
Box1,
Box2
},
  data() {
    return {
      
    };
  },

  mounted() {
    
  },

  methods: {
    
  },
};
</script>
  • 在你点击弹框的时候,会发现第一个盒子1 把弹框的内容给遮盖住了。(如果没有遮盖 那你可以缩放一下你的页面 ,就会看到这个效果) 而我们看过代码就会发现。明明我盒子1的层级是3 盒子2的层级是2,而对话框的层级是8887。按照我们以往的经验。就会感觉对话框的层级那么高。按道理应该是是显示在最上面的。不应该会被盒子1去覆盖呀?

    打开控制台观看样式--我们会发现,我们的弹框组件是在盒子2里面的。

soogif.gif

那么怎么解决呢?

这就需要讲到teleport传送门了,

  • 传送门主要就是可以传递组件的内容,例如从Box1 传送到 Box2.

-接下来我们使用Teleport把对话框组件包起来,使用teleport传送门把弹出框组件给传送出去。

<Teleport to="#model">
  <XtxDialog title="警告" :visible="isShow" @close="handleCloseFn">
      <template #default>
        <p>我是内容</p>
        <p>我是内容</p>
        <p>我是内容</p>
        <p>我是内容</p>
      </template>
      <template #footer>
        <XtxButton type="gray" style="margin-right:20px" @click="isShow = false"></XtxButton>
        <XtxButton type="primary"></XtxButton>
      </template>
    </XtxDialog>
<Teleport>

然后在public里面的index.html加入

<div id="model"></div>

接下来我们在点击弹框 就会发现,弹框不会在被盒子1盖着了。在打开控制台 会看到我们的弹框样式,跟box1 和box2是同级的了。由此 我们的8887最高层级,也会生效了。