Vue 自定义全局消息框组件

消息弹框组件,默认3秒后自动关闭,可设置info/success/warning/error类型

效果图:




文件目录:

Message.vue

<template>
  <transition name="fade">
    <div class="message" :class="type" v-if="visible">
      <i class="icon-type iconfont" :class="'icon-'+type"></i>
      <div class="content">{{content}}
        <i v-if="hasClose" class="btn-close iconfont icon-close" @click="visible=false"></i>
      </div>
    </div>
  </transition>
</template>

<script>
  export default {
    name: "MyMessage",
    data() {
      return {
        content: '',
        time: 3000,
        visible: false,
        type:'info',//'success','warning','error'
        hasClose:false,
      }
    },
    mounted() {
      this.close()
    },
    methods: {
      close() {
        window.setTimeout(() =>{
          this.visible = false
        }, this.time);
      }
    }
  }
</script>

index.js
给Vue添加$my_message方法,
判断参数,使用$mount()给组件手动挂载参数,然后将组件插入页面中

import Vue from 'vue'
import Message from './Message.vue'

const messageBox = Vue.extend(Message)

Message.install = function (options, type) {
  if (options === undefined || options === null) {
    options = {
      content: ''
    }
  } else if (typeof options === 'string' || typeof options === 'number') {
    options = {
      content: options
    }
    if (type != undefined && options != null) {
      options.type = type;
    }
  }

  let instance = new messageBox({
    data: options
  }).$mount()

  document.body.appendChild(instance.$el)

  Vue.nextTick(() => {
    instance.visible = true
  })
}

export default Message

在main.js里全局引入

import Message from '@/components/common/message'
Vue.prototype.$my_message = Message.install;
参数名 类型 说明
content String 内容
time Number 消失时间,默认3秒后消失
type String info/success/warning/error,默认info
hasClose Boolean 是否含关闭按钮,默认false

页面中调用

//简写,第一个参数为内容,第二个为类型

this.$my_message('这是一个message');
this.$my_message('这是一个warning','warning');

//传参的方式

this.$my_message({
    content:'这是一个success提示',
    time:5000000,
    type:'success',
    hasClose:true,
});
原文地址:https://www.cnblogs.com/conglvse/p/9641550.html