用Vue.extend構(gòu)建消息提示組件的方法實例
前提
前段時間自己做的vue練手項目,需要一個通用的消息提示組件,但是消息提示這種組件我更想用方法來調(diào)用,而不是在各個頁面上都添加個組件(那樣感覺很麻煩,重度懶癌患者),于是就上網(wǎng)差查了查,并研究了ElementUI的message源碼。自己弄出來一個簡陋的消息提示組件
Vue.extend是什么
按照官方文檔說法,他是一個類構(gòu)造器,用來創(chuàng)建一個子類vue并返回構(gòu)造函數(shù),而Vue.component它的任務(wù)是將給定的構(gòu)造函數(shù)與字符串ID相關(guān)聯(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ù)不同的類型,設(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;
最后的效果圖
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue新建環(huán)境變量以及網(wǎng)絡(luò)請求工具axios的二次封裝詳解
這篇文章主要為大家介紹了vue新建環(huán)境變量以及網(wǎng)絡(luò)請求工具axios的二次封裝詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06vuejs2.0實現(xiàn)分頁組件使用$emit進行事件監(jiān)聽數(shù)據(jù)傳遞的方法
這篇文章主要介紹了vuejs2.0實現(xiàn)分頁組件使用$emit進行事件監(jiān)聽數(shù)據(jù)傳遞的方法,非常不錯,具有參考借鑒價值,,需要的朋友可以參考下2017-02-02Vue3使用富文本框(wangeditor)的方法總結(jié)
項目中用到了富文本,選來選去選擇了wangeditor,下面這篇文章主要給大家介紹了關(guān)于Vue3使用富文本框(wangeditor)的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-01-01策略模式實現(xiàn) Vue 動態(tài)表單驗證的方法
策略模式(Strategy Pattern)又稱政策模式,其定義一系列的算法,把它們一個個封裝起來,并且使它們可以互相替換。封裝的策略算法一般是獨立的,策略模式根據(jù)輸入來調(diào)整采用哪個算法。這篇文章主要介紹了策略模式實現(xiàn) Vue 動態(tài)表單驗證,需要的朋友可以參考下2019-09-09vue使用ArcGis?API?for?js創(chuàng)建地圖實現(xiàn)示例
這篇文章主要為大家介紹了vue使用ArcGis?API?for?js創(chuàng)建地圖實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08antd-DatePicker組件獲取時間值,及相關(guān)設(shè)置方式
這篇文章主要介紹了antd-DatePicker組件獲取時間值,及相關(guān)設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10