您好,登錄后才能下訂單哦!
前提
前段時(shí)間自己做的vue練手項(xiàng)目,需要一個(gè)通用的消息提示組件,但是消息提示這種組件我更想用方法來(lái)調(diào)用,而不是在各個(gè)頁(yè)面上都添加個(gè)組件(那樣感覺很麻煩,重度懶癌患者),于是就上網(wǎng)差查了查,并研究了ElementUI的message源碼。自己弄出來(lái)一個(gè)簡(jiǎn)陋的消息提示組件
Vue.extend是什么
按照官方文檔說(shuō)法,他是一個(gè)類構(gòu)造器,用來(lái)創(chuàng)建一個(gè)子類vue并返回構(gòu)造函數(shù),而Vue.component它的任務(wù)是將給定的構(gòu)造函數(shù)與字符串ID相關(guān)聯(lián),以便Vue.js可以在模板中接收它。
了解了這點(diǎn)之后我們開始做我們的消息提示組件吧。
消息提示組件
首先我們先創(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ù)不同的類型,設(shè)置不同消息的背景顏色 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()方法調(diào)用
vue.prototype.$message = message;
最后的效果圖
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。