前段时间本身作的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