Vue3 Composition API中Quasar Notify自定义类型复用的最佳实践
Vue3 + Quasar Notify 复用最佳实践
把自定义通知逻辑抽离成Vue3的自定义Composable是最贴合Composition API风格的方案,步骤如下:
1. 封装Composable文件
在项目里新建src/composables/useNotify.js,把通知的注册和调用逻辑都封装进去:
import { useQuasar } from 'quasar' export function useNotify() { const $q = useQuasar() // 注册自定义通知类型 $q.notify.registerType('notifyInfo', { color: 'blue-4', textColor: 'white', icon: 'info', position: 'top-right' // 这里可以加你需要的其他配置,比如timeout、actions等 }) $q.notify.registerType('notifyError', { color: 'red-4', textColor: 'white', icon: 'error', position: 'top-right' }) // 封装调用方法 const notifyInfo = (message) => { $q.notify({ type: 'notifyInfo', message }) } const notifyError = (message) => { $q.notify({ type: 'notifyError', message }) } return { notifyInfo, notifyError } }
2. 在组件中复用
不管哪个组件需要用,直接导入这个Composable就行:
<script setup> import { useNotify } from '@/composables/useNotify' const { notifyInfo, notifyError } = useNotify() // 调用示例 const onSuccess = () => { notifyInfo('操作完成啦!') } const onError = () => { notifyError('出问题了,请重试~') } </script> <template> <q-btn label="成功通知" @click="onSuccess" /> <q-btn label="错误通知" @click="onError" color="negative" /> </template>
可选优化:全局注册通知类型
如果不想每个组件用的时候都注册一次类型,可以把类型注册移到main.js里,这样全局只执行一次:
import { createApp } from 'vue' import { Quasar, Notify } from 'quasar' import App from './App.vue' const app = createApp(App) app.use(Quasar, { plugins: { Notify }, config: { notify: { /* 全局默认配置 */ } } }) // 全局注册自定义类型 app.config.globalProperties.$q.notify.registerType('notifyInfo', { color: 'blue-4', textColor: 'white', icon: 'info', position: 'top-right' }) app.config.globalProperties.$q.notify.registerType('notifyError', { color: 'red-4', textColor: 'white', icon: 'error', position: 'top-right' }) app.mount('#app')
这时Composable可以简化成只提供调用方法:
import { useQuasar } from 'quasar' export function useNotify() { const $q = useQuasar() const notifyInfo = (message) => $q.notify({ type: 'notifyInfo', message }) const notifyError = (message) => $q.notify({ type: 'notifyError', message }) return { notifyInfo, notifyError } }
两种方案选哪个看项目情况:全局注册更高效,Composable内注册更模块化,适合按需引入的场景。
内容的提问来源于stack exchange,提问作者T. Decker
相关产品推荐
相关产品推荐

