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,
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM