美文网首页
vue弹窗类组件的实现

vue弹窗类组件的实现

作者: 李欢li | 来源:发表于2020-02-06 15:42 被阅读0次

弹窗这类组件的特点是它们在当前vue实例例之外独⽴立存在,通常挂载于body;它们是通过JS动态创建 的,不需要在任何组件中声明。常⻅使用姿势

this.$create(Notice, {
      title: '我是一个弹窗哦',
      message: '提示信息', 
      duration: 1000
}).show();

create

create函数⽤用于动态创建指定组件实例例并挂载⾄至body

// 创建指定组件实例并挂载于body上
import Vue from 'vue';
export default function create(Component, props) {
    // 0. 先创建vue实例
    const vm = new Vue({
        render(h) {
            // render方法提供给我们一个h函数,它可以渲染VNode
            return h(Component, {props})
        }
    }).$mount(); // 更新操作
    // 1. 上面vm帮我们创建组件实例
    // 2. 通过$children获取该组件实例
    const comp = vm.$children[0];
    // 3. 追加至body
    document.body.appendChild(vm.$el);
    // 4. 清理函数
    comp.remove = () => {
        document.body.removeChild(vm.$el);
        vm.$destroy();
    }
    // 5. 返回组件实例
    return comp;
}

创建通知组件,Notice.vue

<template>
  <div v-if="isShow">
    <h3>{{title}}</h3>
    <p>{{message}}</p>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    message: {
      type: String,
      default: ""
    },
    duration: {
      type: Number,
      default: ""
    }
  },
  data() {
    return {
      isShow: false
    };
  },
  methods: {
    show() {
      this.isShow = true;
      setTimeout(() => {
          this.hide()
      }, this.duration);
    },
    hide() {
      this.isShow = false;
      this.remove();
    }
  }
};
</script>

<style lang="scss" scoped>
</style>

使⽤

import Notice from "../Notice";
import create from "@/utils/create";
const notice = create(Notice, {
          title: "我是一个弹窗哦", 
          message: "提示信息",
          duration: 1000
   });
   notice.show();

相关文章

网友评论

      本文标题:vue弹窗类组件的实现

      本文链接:https://www.haomeiwen.com/subject/cqhuxhtx.html