I want to know if there's a way to create a reusable scritp/class/service with primevue toast function calls, in such a way that I don't need to call the primevue toast functions directly in every single component.
What I've tried to do up until now, was to create a ToastService.ts like this:
import { useToast } from 'primevue/usetoast';
const toast = useToast();
export function addMsgSuccess(): void {
toast.add({ severity: 'success', summary: 'Test', detail: 'Test', life: 3000 });
}
But this code crashes my application and I get the following error:
Uncaught Error: No PrimeVue Toast provided!at useToast (usetoast.esm.js?18cb:8:1) eval (ToastService.ts?73ba:3:1) Module../src/shared/service/ToastService.ts (app.js:1864:1) webpack_require (app.js:849:30) fn (app.js:151:20) eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/eslint-loader/index.js?!./src/views/cadastro-plano/CadastroPlano.ts?vue&type=script&lang=ts:31:87) Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/eslint-loader/index.js?!./src/views/cadastro-plano/CadastroPlano.ts?
Does anyone know how to solve this problem, or to create functions that make this add() call, so I don't need to call it everysingle time?
6条答案
按热度按时间vkc1a9a21#
在试用了一段时间之后,我发现了一个我认为很优雅的解决方案,尽管它使用了Pinia。使用这个方法,您也可以在帮助函数中调用toast,并且重用函数非常简单。
主文件.ts
界面.ts
使用通知.ts
应用程序版本
任意子组件.vue
帮助函数中的用法示例.ts
jpfvwuh42#
对于答案:above@match,对于那些正在挣扎的人,请将App.vue更改为:
3qpi33ja3#
针对需要在 js 文件中使用吐司的用户的示例
lokaqttq4#
也许下面的解决方案对您有效:
在App.vue中添加一个吐司,并添加一个查看来自商店的消息的手表
商店
然后,在任何其他组件中只更新消息
6fe3ivhb5#
这个解决方案对我很有效,但我不确定它是不是一个好的解决方案。
首先:从main.ts导出应用程序
第二:导入应用程序并使用
app.config.globalProperties
的吐司服务第三步:在组件中导入myToastService。
w1e3prcc6#
另一种选择是在单个位置(
App.vue
)处理toast,然后通过消息总线接收它们。首先在
main.js
中设置总线:然后将总线注入App.vue,侦听事件并生成Toast:
然后再送上一份分量的吐司词:
或从非组件代码: