我想使用PrimeVue庫中的 Toast 組件,我還想為它創建一個很好的可重用服務,但我收到了這個錯誤。如果我不嘗試為 Toast 通知提取單獨的服務,這似乎不是問題。
但我確實想useToast()從我的自定義服務內部呼叫,而不是直接在組件的setup函式中呼叫。
我正在使用Vue 3.2.25最新Vite.js 2.9.9版本的PrimeVue
[Vue warn]: inject() can only be used inside setup() or functional components.
[Vue warn]: Unhandled error during execution of native event handler
at <App>
Uncaught Error: No PrimeVue Toast provided!
at useToast (usetoast.esm.js:8:15)
at Proxy.showToast (toastService.js:4:19)
at _createElementVNode.onClick._cache.<computed>._cache.<computed> (App.vue:4:21)
at callWithErrorHandling (runtime-core.esm-bundler.js:155:22)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21)
at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:369:13)
這是一個 CodeSandbox 鏈接:https ://codesandbox.io/s/prime-vue-toast-issue-owcio8?file=/src/services/toastService.js
這是我的main.js
import App from './App.vue'
import { createApp } from 'vue'
import PrimeVue from 'primevue/config';
import 'primevue/resources/primevue.min.css';
import 'primevue/resources/themes/lara-dark-blue/theme.css';
import ToastService from 'primevue/toastservice';
const app = createApp(App);
app.use(PrimeVue);
app.use(ToastService);
app.mount('#app')
這是我的App.vue
<template>
<Toast />
<button @click="showToast">Show toast!</button>
</template>
<script setup>
import Toast from 'primevue/toast';
import { showToast } from './services/toastService';
</script>
這是我的toastService.js:
import { useToast } from "primevue/usetoast";
const showToast = () => {
const toast = useToast();
toast.add({ severity: 'info', detail:'Hello' });
}
export { showToast }
uj5u.com熱心網友回復:
Vue 可組合物件主要應該在創建組件實體時直接在 setup 函式中使用。其中一些可以在其他地方使用,但這取決于可組合的實作,應該另外確認。
該錯誤表明在內部useToast使用inject,這限制了此可組合的使用。
對于可重用的服務,它可以是:
import { useToast } from "primevue/usetoast";
export const useToastService = () => {
const toast = useToast();
const showToast = () => {
toast.add({ severity: 'info', detail:'Hello' });
}
return { showToast };
};
并使用如下:
const { showToast } = useToastService();
PrimeVueToast實作中實際上不需要使用useToast可組合,它是一個方便的助手;看到這個和這個。由于在下一次主要庫更新中重構 toast 服務存在一些風險,因此可以將其簡化為使用:
import ToastEventBus from 'primevue/toasteventbus';
export const useToastService = () => {
const showToast = () => {
ToastEventBus.emit('add', { severity: 'info', detail:'Hello' });
}
return { showToast };
};
通過這種方式,可以在應用程式的任何位置(例如在路由器中)謹慎使用該服務。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482415.html
標籤:javascript Vue.js Vuejs3 主播
