我爱模板网再做一个小项目,不想使用element plus、antd这种重量级框架,但是又觉得element plus的提示插件很美观,于是就自己动手封装了一个轻量级的,不依赖任何插件的toat提示插件。
先看下插件效果:

插件npm地址:https://www.npmjs.com/package/hxz-light-toast?activeTab=readme
封装流程:
1、Vue CLI创建项目,项目名叫:hxz-light-toast
1 | vue create hxz-light-toast |
2、修改文件夹
将src文件夹重命名为test,用来测试插件,并且复制一份src文件夹,用来编写插件,删除src/App.vue。
3、修改package.json中的scripts如下:
2 | "test" : "vue-cli-service serve test/main.js" , |
3 | "build" : "vue-cli-service build --target lib --name index src/main.js" |
其中test脚本是配置测试demo的启动,与正常的 vue 项目启动一致,只是修改了一下路径跟脚本名。因为是开发的一个插件,打包时不能像普通vue项目一样打包成应用,而是要打包成库。Vue脚手架(Vue CLI)可以直接打包库,命令如下:
1 | vue-cli-service build --target lib --name myLib [entry] |
4、在src的components下新建hxz-light-toast.vue:
02 | <Transition name= 'fade' > |
03 | <div v- if = "isShow" :class= "['message', tipType]" >{{ tipText }}</div> |
07 | import { ref, defineExpose } from 'vue' ; |
08 | const isShow = ref( false ) |
09 | const tipText = ref( '默认提示内容' ) |
10 | const tipType = ref( 'info' ) |
11 | const show = (str, type = 'info' , time = 2000) => { |
19 | const hide = () => isShow.value = false |
27 | background: #edf2fc url('../assets/icon-info.png') no-repeat 20px center/14px 14px; |
29 | border: 1px solid #ebeef5; |
32 | padding: 0 20px 0 45px; |
37 | transform: translate(-50%, 0); |
42 | background-color: #edf2fc; |
43 | background-image: url( '../assets/icon-info.png' ); |
45 | border: 1px solid #ebeef5; |
48 | background-color: #f0f9eb; |
49 | background-image: url( '../assets/icon-success.png' ); |
51 | border: 1px solid #e1f3d8; |
54 | background-color: #fef0f0; |
55 | background-image: url( '../assets/icon-error.png' ); |
57 | border: 1px solid #fde2e2; |
60 | background-color: #fdf6ec; |
61 | background-image: url( '../assets/icon-warning.png' ); |
63 | border: 1px solid #faecd8; |
67 | transform:translate(-50%, -100px) |
70 | transition: all 500ms linear; |
74 | transform: translate(-50%, 0) |
78 | transform: translate(-50%, 0) |
81 | transition: all 500ms linear; |
85 | transform:translate(-50%, -100px) |
5、在src/main.js导出插件:
01 | import { createVNode, render } from 'vue' |
02 | import Toast from './hxz-light-toast.vue' |
06 | const Vnode = createVNode(Toast) |
08 | render(Vnode, document.body) |
10 | app.config.globalProperties.$toast = { |
13 | Vnode.component?.exposed?.show(str, time) |
上面的代码解释的很清楚了,这里不再多说。
6、测试插件
在test的App.vue配置如下代码来测试插件:
08 | this.$toast.show('这是一条消息提示') |
运行,没有问题,效果见文章开头的图片
至此,插件就封装好了。
打包发布见:编写一个vue3插件并发布它