6-传送组件


传送组件

1、知识点

Vue 鼓励我们将 UI 及其相关行为封装成组件,我们可以将这些组件嵌套在一起以构成应用程序 UI 的树。但是有时候组件模板的一部分在逻辑上是属于该组件的,最好的做法是将该模板的这部分移到 Vue 应用程序外部的 DOM 的其他位置。

  • teleport 传送组件
  • to 属性
  • disabled 属性
  • teleport 组件更新

2、teleport 传送组件

常见的情况下是在创建一个包含全屏模式的组件。在大多数情况下,我们希望模态框的逻辑存在于组件中,但是模态框的定位很难通过 CSS 来解决,或者需要更改组件的组成部分。

首先来想一个组件 modal-button,该组件将具有一个 button 元素来触发模态框的打开,以及一个 div 具有的类名的元素 .modal,其中将包含模态框的内容和一个用于自动关闭的按钮。

src/views/ 新建 ModalButton.vue,代码如下:

<template>
  <div>
    <button @click="modalOpen = true">Open full screen modal!</button>

    <div v-if="modalOpen" class="modal">
      <div>
        I'm a modal!
        <button @click="modalOpen = false">Close</button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "modalButton",
    data() {
      return {
        modalOpen: false,
      };
    },
  };
</script>

我们可以看到一个问题,深度嵌套 divposition: absolute 模态框相对定位于父级元素 div 作为参考。

<style lang="scss" scoped>
.modal {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.modal div {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: white;
    width: 300px;
    height: 300px;
    padding: 5px;
}
</style>

src/views/ 新建 tele.vue,代码如下:

<template>
  <div>
    <modal-button></modal-button>
  </div>
</template>

<script>
  import modalButton from "./ModalButton";
  export default {
    name: "tele",
    components: {
      modalButton,
    },
  };
</script>

src/router/index.js 中添加路由

const routes = [
  {
    path: "/tele",
    name: "tele",
    component: () => import("../views/tele.vue"),
  },
];

App.vue 添加导航

<router-link to="/tele">tele</router-link>
|

3、to 属性

Teleport 提供了一种干净的方式,允许我们控制在 DOM 中哪个⽗节点下呈现 HTML,而不必污染全局状态或将其拆分为两个组件。

修改 modal-button 来使用并告诉 Vue “teleport this HTML to the body” 标签。

<template>
  <div>
    <button @click="modalOpen = true">Open full screen modal!</button>
    <teleport to="body">
      <div v-if="modalOpen" class="modal">
        <div>
          I'm a teleported modal! (My parent is "body")
          <button @click="modalOpen = false">Close</button>
        </div>
      </div>
    </teleport>
  </div>
</template>

运行代码,我们看到模态框被移到了 body 中。

图片描述

4、diabled 属性

teleport 组件添加 disabled 属性。

<template>
  <div>
    <button @click="modalOpen = true">Open full screen modal!</button>

    <teleport to="body" :disabled="true">
      <div v-if="modalOpen" class="modal">
        <div>
          I'm a teleported modal! (My parent is "body")
          <button @click="modalOpen = false">Close</button>
        </div>
      </div>
    </teleport>
  </div>
</template>

效果如下:

图片描述

使用 disabled 属性,设置为 true,告诉 teleport 传送组件不要将模态框移除到 body 下。

5、总结

学习了使用 teleport 组件实现模态框,学习了两大属性:

  • to 表示将模态框放置在什么位置。

文章作者: Syhan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Syhan !
评论
  目录