I can't use pinia outside of component setup #664
-
When I try to use it in the api.ts I get this error: When I try to use it in the router.ts I get this error: const pinia = createPinia() |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
That error is happening because you are trying to create a store before calling Have a look at the docs here: https://pinia.esm.dev/core-concepts/outside-component-usage.html
I can't see in your screenshots above where exactly you planned on using the userStore, but if it's in an Axios interceptor then call it within the interceptor function: axios.interceptors.request.use(function (config) {
const userStore = useUserStore()
config.headers.Authorization = userStore.token
return config
}); Or if it's in something like a router guard then you need to call the user store within the guard itself: router.beforeEach((to) => {
const userStore = useUserStore()
if (!userStore.isLoggedIn) return '/login'
}) |
Beta Was this translation helpful? Give feedback.
-
请问 你是使用的 vscode吗 你的主题是啥 |
Beta Was this translation helpful? Give feedback.
That error is happening because you are trying to create a store before calling
app.use(pinia)
(or however you are initializing it)Have a look at the docs here: https://pinia.esm.dev/core-concepts/outside-component-usage.html
Most importantly:
I can't see in your screenshots above where exactly you planned on using the userStore, but if it's in an Axios interceptor then call it within the interceptor function: