vue2实现传送门效果

描述: 在Vue3中<Teleport> 是一个内置组件,使我们可以将一个组件的一部分模板“传送”到该组件的 DOM 层次结构之外的 DOM 节点中;现在在vue2实现一下效果:将组件挂载到body上

先看效果:

 

 代码:

Teleport 组件:


<script>
export default {
  props: {
    to: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      required: true
    }
  },
  inject: ['parent'],
  //   inject 选项应该是:
  // 一个字符串数组,或 一个对象,对象的 key 是本地的绑定名,value 是:
  //     在可用的注入内容中搜索用的 key (字符串或 Symbol),或
  //     一个对象,该对象的:
  //          from property 是在可用的注入内容中搜索用的 key (字符串或 Symbol)
  //          default property 是降级情况下使用的 value

  // Vue 选项中的 render 函数若存在,则 Vue 构造函数不会从 template 选项或通过 el 选项指定的挂载元素中提取出的 HTML 模板编译渲染函数。
  render() {
    return <div class="Teleport">{this.$scopedSlots.default()}</div>
    // $scopedSlots用来访问作用域插槽。对于包括 默认 slot 在内的每一个插槽,该对象都包含一个返回相应 VNode 的函数。
  },
  watch: {
    disabled() {
      if (!this.disabled) {
        // this指向组件的实例。$el指向当前组件的DOM元素。
        document.querySelector(this.to).appendChild(this.$el);
      } else {
        this.parent.toSourceDom(this.$el);
      }
    }
  },
  mounted() {
    if(!this.disabled) document.querySelector(this.to).appendChild(this.$el)
  },
  methods: {},
};
</script>
<style lang="scss" scoped>
.Teleport {
  width: 100%;
  height: 100%;
}
</style>

index.vue 中引用 Teleport.vue 组件

<template>
  <div>
    <Teleport v-if="isShow" :disabled="isTeleport" to="body">
      <div class="cover">
        <div class="inner">
          我是弹窗
          <div class="close" @click="closed">关闭按钮</div>
        </div>
      </div>
    </Teleport>
    <button @click="show">显示</button>
  </div>
</template>
<script>
import Teleport from "./Teleport.vue";
import model from "./model.vue";
export default {
  data() {
    return {
      isShow: false, // 控制 Teleport 组件挂载时机
      isTeleport: false, // 控制什么时候被传送
    };
  },
  provide() {
    return {
      parent: this,
    };
  },
  components: { Teleport, model },
  methods: {
    show() {
      this.isShow = true;
    },
    closeModel() {
      this.isShow = false;
    },
    toSourceDom(dom) {
      document.getElementById("sourceBox").appendChild(dom);
    },
  },
};
</script>
<style lang="scss" scoped>
.cover {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba($color: #000000, $alpha: 0.3);
  .inner {
    width: 500px;
    height: 300px;
    border-radius: 10px;
    background: #fff;
    color: red;
    font-weight: 600;
    position: absolute;
    left: 40%;
    top: 30%;
    text-align: center;
    font-size: 30px;
    .close{
      position: absolute;
      bottom: 0;
      right: 0;
      background: skyblue;
      padding: 10px;
      cursor: pointer;
      border-radius: 10px 0 0 0;
    }
  }
}
</style>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值