从零开始实现Vue简单的Toast插件
作者:FatGe 时间:2024-05-13 09:13:55
前言
一直都觉得vue的插件生涩难懂,但是又很好奇,在看了几篇文章,试着写了写之后觉得也没那么难,本文主要实现一个简单的Toast插件,方便迁移到不同的项目中,用来全局提示、警告一些信息。
概述:
在前端项目中,有时会需要通知、提示一些信息给用户,尤其是在后台系统中,操作的正确与否,都需要给与用户一些信息。
1. 实例
在Vue组件的methods内,调用如下代码
this.$toast({
content: "可自动关闭",
autoClose: true
})
在页面的右侧会出现一个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 = {}) => {
/* 创建一个Toast组件的实例 */
let instance = generateInstance(options)
/* 将单个toast存入队列中 */
instances.push(instance)
}
当调用该方法时,通过generateInstance创建一个Toast组件的实例,并将其放入instances,统一管理。
/* 构造单个toast */
const ToastConstructor = Vue.extend(Toast)
const verticalOffset = 16
function generateInstance(options) {
// 利用ToastConstructor创建一个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)
//监听组件close
instance.$once('toastClose', function () {
const curInstance = this
// 当Toast组件关闭时,重新计算垂直方向的偏移量
updateVerticalOffset(curInstance)
typeof curInstance.onClose === 'function' && curInstance.onClose()
})
return instance;
}
generateInstance函数中,首先利用ToastConstructor构造函数创建一个Toast组件的实例,并通过propsData传入属性值,同时通过$mount(document.createElement('div'))
渲染该组件。
ToastConstructor是通过Vue.extend创造Toast组件的构造函数,关于这部分的具体原理,可以参考
基于Vue构造器创建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组件的创建、如何在页面中初始化、更新的位置。
Toast组件
组件的功能比较简单,只需要展示信息,以及具备自动关闭、手动关闭两个功能,属性也要包括Toast的类型、位置、内容等。
组件的生命周期
let instance = new ToastConstructor({
propsData: options
}).$mount(document.createElement('div'))
当Toast组件$mount调用时,会触发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插件,提取不同业务之间公共的部分,减少业务的工作量。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对asp之家的支持。
来源:https://juejin.im/post/5c036e4fe51d451b80257c45
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Pytorch中torch.stack()函数的深入解析
![](https://img.aspxhome.com/file/2023/9/115029_0s.png)
python中数组和矩阵乘法及使用总结(推荐)
Python dict的常用方法示例代码
Golang import 导入包语法及一些特殊用法详解
jupyter notebook 写代码自动补全的实现
![](https://img.aspxhome.com/file/2023/6/101436_0s.png)
python消费kafka数据批量插入到es的方法
delete from online where datediff
Python面向对象编程基础解析(一)
python实现的多线程端口扫描功能示例
![](https://img.aspxhome.com/file/2023/3/118613_0s.png)
Python编程图形库之Pillow使用方法讲解
![](https://img.aspxhome.com/file/2023/5/80425_0s.png)
Python去除字符串前后空格的三种方法汇总
![](https://img.aspxhome.com/file/2023/5/106985_0s.png)
Python实现指定数组下标值正序与倒序排序算法功能举例
![](https://img.aspxhome.com/file/2023/1/103751_0s.png)
用一条SQL实现:一行多个字段数据的最大值
python两种获取剪贴板内容的方法
![](https://img.aspxhome.com/file/2023/8/127118_0s.png)
Vue+ECharts实现中国地图的绘制及各省份自动轮播高亮显示
![](https://img.aspxhome.com/file/2023/0/132960_0s.gif)
Python+Pygame制作"长沙版"大富翁
![](https://img.aspxhome.com/file/2023/8/65088_0s.png)
br玩转清除浮动
Android中Okhttp3实现上传多张图片同时传递参数
解析PyCharm集成GitLab代码仓的问题
![](https://img.aspxhome.com/file/2023/1/109881_0s.png)
教你使用pyqt实现桌面歌词功能
![](https://img.aspxhome.com/file/2023/6/127106_0s.gif)