Vue中新建弹窗组件,帮助理解Vue原理

1. Notice弹窗组件
<template>
  <div class="box" v-if="isShow">
      <h3>{{ title }}</h3>
      <p class="box-content">{{ message }}</p>
  </div>
</template>

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

<style scoped>
.box {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
  text-align: center;
  pointer-events: auto;
  background-color: rgba(1, 1, 1, 0.1);
}
.box-content {
  width: 200px;
  margin: 10px auto;
  font-size: 14px;
  padding: 8px 16px;
  background-color: #fff;
  border-radius: 3px;
  margin-bottom: 8px;
}
</style>

2.创建create.js文件
// 1.创建传入的组件实例
// 2.挂载它从而生成dom结构
// 3.将生成的dom结构追加到body上
// 4.一个淘汰机制:就是不需要的时候组件实例应当被销毁,防止内存泄漏

import Vue from 'vue'

export default function create(Component, props) {
    // 创建传入的组件实例
    // 第一种,Vue.extend({});
    // 这是第二种
    const vm = new Vue({
        render(h) {
            // h 既是createElement(tag, data, children)
            // 放回虚拟dom
            return h(Component, { props });
        },
        // 只挂载,不设置主元素,意思是执行初始化的过程,但没有追加dom的操作
    }).$mount();

    // 将生成的dom元素追加到body上
    document.body.appendChild(vm.$el);

    // 获取组件实例
    const comp = vm.$children[0];

    // 给组件实例添加一个销毁的方法
    comp.remove = () => {
        // 移除dom
        document.body.removeChild(vm.$el);
        vm.$destroy();
    };

    return comp;
}

3.main.js文件中全局注册
import create from './plugins/create'
Vue.prototype.$create = create;

4.在组件中使用
import Notice from "../components/Notice";
showDialog() {
      this.$create(Notice, {
        title: '提示',
        message: '这是一段提示',
        duration: 10000
      }).show();
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容