前言

之前有跟着百度上的一些文章写过类似的,不过写的比较复杂

于是我就看了看ElementUI中关于消息提示这块的源码,虽然说代码量也蛮大的,不过也是因为有多种表现形式的原因,所以只需要取其中比较关键的代码即可

this.$message('这是一条消息提示');
this.$message({
          message: '恭喜你,这是一条成功消息',
          type: 'success'
});
this.$message({
          message: '警告哦,这是一条警告消息',
          type: 'warning'
});
this.$message.error('错了哦,这是一条错误消息');

Code

这边写的是一个图片放大的全局组件,大概就是通过一个js事件来打开放大一张图片,然后点击空白处关闭

Vue File

<template>
  <div name="image-dialog">
    <transition name="ani">
      <div class="border" v-if="show" @click="show = false">
        <div class="content">
          <img @click.stop :src="url" alt=""/>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "ImageDialog",
  data() {
    return {
      url: "",
      show: false,
    }
  }
}
</script>

<style lang="scss" scoped>
.ani-enter-active,
.ani-leave-active {
  opacity: 1;
  transition: all 0.3s;
}

.ani-enter,
.ani-leave-to {
  opacity: 0;
}

.border {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, .3);
}
</style>

JS File

import Vue from 'vue';
import ImageDialog from "./ImageDialog"

// 构造Vue实例
let vueEl = Vue.extend(ImageDialog);

const Main = function(url) {
  let instance = new vueEl();
  instance.$mount();
  instance.url = url;
  instance.show = true;
  document.body.appendChild(instance.$el);
};

// 全局注册
const registry = function (){
  Vue.prototype.$ImageDialog = Main;
}

export default registry;

在main.js中的配置

import ImageDialog from "./components/xm-tools/ImageDialog/index";
Vue.use(ImageDialog);

Use

this.$ImageDialog("https://qwq.link/images/avatar.jpg");

Ex - ploooosion!