用Vue.extend構建消息提示組件的方法實例
前提
前段時間自己做的vue練手項目,需要一個通用的消息提示組件,但是消息提示這種組件我更想用方法來調用,而不是在各個頁面上都添加個組件(那樣感覺很麻煩,重度懶癌患者),于是就上網差查了查,并研究了ElementUI的message源碼。自己弄出來一個簡陋的消息提示組件
Vue.extend是什么

按照官方文檔說法,他是一個類構造器,用來創(chuàng)建一個子類vue并返回構造函數(shù),而Vue.component它的任務是將給定的構造函數(shù)與字符串ID相關聯(lián),以便Vue.js可以在模板中接收它。
了解了這點之后我們開始做我們的消息提示組件吧。
消息提示組件
首先我們先創(chuàng)建我們的提示組件的模板
<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();
//根據(jù)不同的類型,設置不同消息的背景顏色
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()方法調用
vue.prototype.$message = message;
最后的效果圖

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue中transition單個節(jié)點過渡與transition-group列表過渡全過程
這篇文章主要介紹了Vue中transition單個節(jié)點過渡與transition-group列表過渡全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
vue封裝自定義指令之動態(tài)顯示title操作(溢出顯示,不溢出不顯示)
這篇文章主要介紹了vue封裝自定義指令之動態(tài)顯示title操作(溢出顯示,不溢出不顯示),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

