從零開始實現(xiàn)Vue簡單的Toast插件
前言
一直都覺得vue的插件生澀難懂,但是又很好奇,在看了幾篇文章,試著寫了寫之后覺得也沒那么難,本文主要實現(xiàn)一個簡單的Toast插件,方便遷移到不同的項目中,用來全局提示、警告一些信息。
概述:
在前端項目中,有時會需要通知、提示一些信息給用戶,尤其是在后臺系統(tǒng)中,操作的正確與否,都需要給與用戶一些信息。
1. 實例
在Vue組件的methods內,調用如下代碼
this.$toast({
content: "可自動關閉",
autoClose: true
})
在頁面的右側會出現(xiàn)一個Toast彈框,多次點擊時,會依照順序進行顯示,并且Toast可自動關閉,具體效果如圖。

代碼地址:Github UI-Library
2. 原理
代碼結構
將Toast插件分為兩個部分:
- Toast組件本身,包含本身的dom結構以及data,并在其生命周期完成在頁面中的掛載與銷毀;
- 在組件外構建一層代理并提供相關方法用于調用、并控制多個Toast在頁面中顯示的順序。
Toast方法
為了能夠通過this.$toast({...})調用Toast組件,須在Vue的prototype上添加一個方法,如下
let instances = []
let initIndex = 0
Vue.prototype.$toast = (options = {}) => {
/* 創(chuàng)建一個Toast組件的實例 */
let instance = generateInstance(options)
/* 將單個toast存入隊列中 */
instances.push(instance)
}
當調用該方法時,通過generateInstance創(chuàng)建一個Toast組件的實例,并將其放入instances,統(tǒng)一管理。
/* 構造單個toast */
const ToastConstructor = Vue.extend(Toast)
const verticalOffset = 16
function generateInstance(options) {
// 利用ToastConstructor創(chuàng)建一個Toast的實例
let instance = new ToastConstructor({
propsData: options
}).$mount(document.createElement('div'))
if (typeof options.onClose === 'function') instance.onClose = options.onClose
//計算instance verticalOffset
let id = 'toast_' + initIndex++
instance.id = id
// 初始化Toast在空間中的垂直偏移量
instance.verticalOffset = initVerticalOffset(instance.position)
//監(jiān)聽組件close
instance.$once('toastClose', function () {
const curInstance = this
// 當Toast組件關閉時,重新計算垂直方向的偏移量
updateVerticalOffset(curInstance)
typeof curInstance.onClose === 'function' && curInstance.onClose()
})
return instance;
}
generateInstance函數(shù)中,首先利用ToastConstructor構造函數(shù)創(chuàng)建一個Toast組件的實例,并通過propsData傳入屬性值,同時通過$mount(document.createElement('div'))渲染該組件。
ToastConstructor是通過Vue.extend創(chuàng)造Toast組件的構造函數(shù),關于這部分的具體原理,可以參考
基于Vue構造器創(chuàng)建Form組件的通用解決方案。
/* 初始化每個toast對象在頁面中的垂直屬性 */
function initVerticalOffset(position) {
// 篩選同一方向的Toast組件
let typeInstances = instances.filter(item => item.position === position)
// 計算偏移量
return typeInstances.reduce((sum, elem) =>
(elem.$el.offsetHeight + sum + verticalOffset),
verticalOffset)
}
之后當某個Toast關閉時,需要更新所有Toast實例在頁面中偏移量
/* 更新每個toast對象在頁面中的垂直屬性 */
function updateVerticalOffset(removeInstance) {
let index = 0
let removeHeight = removeInstance.verticalOffset
instances.find((elem, i) => {
if (elem.id === removeInstance.id) index = i
})
// 刪除關閉的Toast組件
instances.splice(index, 1)
// 更新在刪除位置之后的組件的位置
for (; index < instances.length; ++index) {
if (instances[index].position === removeInstance.position) {
[instances[index].verticalOffset, removeHeight] =
[removeHeight, instances[index].verticalOffset]
}
}
}
以上完成了Toast組件的創(chuàng)建、如何在頁面中初始化、更新的位置。
Toast組件
組件的功能比較簡單,只需要展示信息,以及具備自動關閉、手動關閉兩個功能,屬性也要包括Toast的類型、位置、內容等。
組件的生命周期
let instance = new ToastConstructor({
propsData: options
}).$mount(document.createElement('div'))
當Toast組件$mount調用時,會觸發(fā)mounted的生命周期
mounted() {
// 掛載Toast在頁面中
document.body.appendChild(this.$el);
// 需要自動關閉時,調用startTimer
if (this.autoClose) this.startTimer();
},
beforeDestroy() {
this.stopTimer();
this.$el.removeEventListener("transitionend", this.destroyElement);
},
destroyed() {
// 注銷
this.$el.parentNode.removeChild(this.$el);
}
自動關閉
需要自動時,就要在利用setTimeout完成該功能,并在注銷時clearTimeout掉,防止泄露。
startTimer() {
if (this.duration > 0) {
this.timer = setTimeout(() => {
if (!this.closed) {
this.close();
}
}, this.duration);
}
},
stopTimer() {
if (this.timer) clearTimeout(this.timer);
}
3. 使用
進一步將其封裝成Vue的插件
export default {
install (Vue) {
Vue.prototype.$toast = (options = {}) => {...}
}
}
并且對所需要傳入的必需屬性,做處理異常處理
export default {
install (Vue) {
Vue.prototype.$toast = (options = {}) => {...}
}
}
4. 總結
通過封裝一個Toast插件,提取不同業(yè)務之間公共的部分,減少業(yè)務的工作量。
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
vue頁面渲染數(shù)組中數(shù)據(jù)文案后添加逗號最后不加
這篇文章主要為大家介紹了vue頁面渲染數(shù)組中數(shù)據(jù)文案后添加逗號最后不加逗號示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
Vite中使用Ant?Design?Vue3.x框架教程示例
這篇文章主要為大家介紹了Vite中使用Ant?Design?Vue3.x框架教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
打通前后端構建一個Vue+Express的開發(fā)環(huán)境
這篇文章主要介紹了打通前后端構建一個Vue+Express的開發(fā)環(huán)境,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Vue2 Element Schema Form 配置式生成表單的實現(xiàn)
本文主要介紹了Vue2 Element Schema Form 配置式生成表單的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05
詳解TypeScript+Vue 插件 vue-class-component的使用總結
這篇文章主要介紹了TypeScript+Vue 插件 vue-class-component的使用總結,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02

