uniapp官方提供的toast组件样式单一 很多时候不满足我们业务
- 我们要实现自定义toast组件要在全局或导入注册,然后在template里写入组件,在this.$refs.toast.open()调用
- 每个组件都要这么做的话,过于繁琐,有没有可以直接调用的方法
- 官方并没有提供解决方法
查阅相关文档看到这篇文章,是基于vue-inset-loader实现的,他是在每个组件在编译时自动写入组件标签,组件要在全局注册
我基于这个思路实现了一个vite+vue3的uniapp的组件插入插件@yck-web/vite-plugin-template-inset; 记录使用方法如下:
-
vite+vue3创建的项目可以在根目录创建vite.config.js文件
import { defineConfig } from 'vite'; import uni from '@dcloudio/vite-plugin-uni'; import vitePluginTemplateInset from "@yck-web/vite-plugin-template-inset" export default defineConfig({ plugins: [ vitePluginTemplateInset(["<my-messsage ref='message'></my-messsage>"]), uni() ], });
- vitePluginTemplateInset插件一定要写在uni()前面,否则不生效,vitePluginTemplateInset里写入你想写入的组件标签,定义一个ref便于组件调用。
- 组件一定要在main.js里全局注册才行
- 组件标签template name="message"一定要写一个名称 避免这个组件也被自动写入组件标签
<template name="message"> <view class="mask" v-show="show"> <view class="dialog"> dialog--- </view> </view> </template>
这样就可以在组件里直接调用this.$refs.message.open()