前段時間本身作的vue練手項目,須要一個通用的消息提示組件,可是消息提示這種組件我更想用方法來調用,而不是在各個頁面上都添加個組件(那樣感受很麻煩,重度懶癌患者),因而就上網差查了查,並研究了ElementUI的message源碼。本身弄出來一個簡陋的消息提示組件vue
按照官方文檔說法,他是一個類構造器,用來建立一個子類vue並返回構造函數,而Vue.component它的任務是將給定的構造函數與字符串ID相關聯,以便Vue.js能夠在模板中接收它。
瞭解了這點以後咱們開始作咱們的消息提示組件吧。app
首先咱們先建立咱們的提示組件的模板dom
<template> <transition name="message-fade"> <div class="message" v-show="show"> <span class="icon"><icon name="info"></icon></span> <p>{{message}}</p> </div> </transition> </template> <script> export default { name: 'v-message', mounted(){ this.StartTime(); }, data(){ return { message: '123', show: false, timer: null } }, methods:{ StartTime(){ this.show = true; if(this.timer){ clearTimeOut(this.timer) }else{ this.timer = setTimeout(()=>{ this.show = false }, 3000); } } } } </script>
以後咱們須要用將message.vue傳到Vue.extend()裏函數
import Vue from 'vue'; let MessageBox = Vue.extend(require('./message.vue')); let instance; var message = function(options){ if(typeof options === 'string'){ options = { message: options } } //生成組件 instance = new MessageBox({ data: options }) //組件須要掛載在dom元素上 instance.vm = instance.$mount(); //根據不一樣的類型,設置不一樣消息的背景顏色 if(options.type){ instance.vm.$el.children[0].className += ` icon__${options.type}`; } document.body.appendChild(instance.vm.$el); return instance.vm; } const type = ['success', 'info', 'warning', 'error']; type.forEach((type)=>{ message[type] = options =>{ if(typeof options === 'string'){ options = { message: options } } options.type = type; return message(options); } }) export default message;
以後用掛在全局方法上,以後用this.$message()方法調用ui
vue.prototype.$message = message;
最後的效果圖this