用全局api的形式实现this.$dialog

一、新建index.vue,编写显示层。

<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: 3000,
    },
  },
  data() {
    return {
      isShow: false,
    };
  },
  methods: {
    show() {
      this.isShow = true;
      setTimeout(this.hide, this.duration);
    },
    hide() {
      this.isShow = false;
      this.remove();
    },
  },
};
</script>
<style>
.box {
  position: fixed;
  width: 100%;
  top: 16px;
  left: 0;
  text-align: center;
  pointer-events: none;
  background-color: #fff;
  border: grey 3px solid;
  box-sizing: border-box;
}
.box-content {
  width: 200px;
  margin: 10px auto;
  font-size: 14px;
  padding: 8px 16px;
  background: #fff;
  border-radius: 3px;
  margin-bottom: 8px;
}
</style>

2、新建index.j文件,用于显示层的显示。

//1、导入vue
import Vue from "vue";

// 2、渲染组件
export default function create(Component, props) {
const vm = new Vue({
render: h=>(Component, props)
}).$mount();

// 3、挂载到根节点上
document.body.appenChild(vm.$el)

const comp = vm.$children[0]

comp.remove = () => {
    document.removeChild(vm.$el)
   vm.$destory()
 }
}

3、创建dialog.js引入对应的文件,使用install方法插件安装到全局

import create from './index.js';
import Dialog from './index.vue';

export default {
install(Vue) {
    Vue.prototype.$dialog = (props) => {
      const comp = create(Dialog, props)
      comp.show()
      return comp
    }
  }
}

4、在main.js文件中引入插件并使用

import Dialog from './dialog.js

Vue.use(Dialog)

5、使用

this.$dialog({
   title: "dialog",
   message: "dialog弹层",
});

效果入下,三秒以后自动消失


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容