关于javascript:Vue3中的Teleport传送门

6次阅读

共计 1175 个字符,预计需要花费 3 分钟才能阅读完成。

动画片多啦 A 梦置信大家很多都看过,而且近几年又呈现了相干的电影,作为小编一个男生来说,始终是对外面的静香朝思暮想,有点跑偏了哈,明天小编介绍的 Teleport 就和多啦 A 梦的任意门一样,能够穿梭到任何的 DOM 中的任何中央
模态框始终是理论开发中用到比拟多的性能之一,在没有各种各样的组件之前,咱们须要通过 css 中的定位对元素进行润饰,有了 Teleport,咱们就能够这样实现一个简略的模态的组件

<style>
  .area{
      position: absolute;
      left: 50%;
      top:50%;
      transform: translate(-50%,-50%);/*  */
      width: 200px;
      height: 300px;
      background:green;
  }
  .mask{
      position: absolute;
      left:0;
      right:0;
      top:0;
      bottom:0;
      background: #000;
      opacity: 0.5;
  }
</style>
<script>
  const app = Vue.createApp({data(){
          return {show:false}
      },
      methods:{handleBtnClick(){this.show = !this.show}
      },
      template: `<div class="area">
              <button @click="handleBtnClick"> 按钮 </button>
              <teleport to="body">
                  <div class="mask" v-show="show"></div>
              </teleport>
              </div>`
  })

  const vm = app.mount("#root")
</script>

下面的例子是将元素传递到 body 中,如果要将元素传递到指定的 DOM 节点,咱们要怎么解决呢?
咱们通过 Teleport 中的 to 属性,能够将代码写成这样

<body>
  <div id="root"></div>
  <div id="hello"></div>
</body>
<script>
  const app = Vue.createApp({data(){
          return {show:false}
      },
      methods:{handleBtnClick(){this.show = !this.show}
      },
      template: `<div class="area">
        <button @click="handleBtnClick"> 按钮 </button>
         // 相似 css 选择器,依据 DOM 元素不同,通过 to 属性设置传送的地位
        <teleport to="#hello">
          <div class="mask" v-show="show"></div>
        </teleport>
      </div>`
  })

  const vm = app.mount("#root")
</script>

大家还能够扫描二维码,关注我的微信公众号,蜗牛全栈。

正文完
 0