I want to use useRoute
in my component which is called in onMounted hook.
Something similar
import { checkUserAuth } from '@/common/CheckUserAuth' onMounted(async () => { await checkUserAuth() })
CheckUserAuth.ts is:
import { useRouter } from 'vue-router' const router = useRouter() // here router is undefined export const checkUserAuth = async () => { const userStore = useUserStore() const userApi = new UserApi() const token = localStorage.getItem(TOKEN_NAME) const router = useRouter() // and here too router is undefined if (!token) { await router.push({ name: LOGIN_PAGE_ROUTE }) return } const userData = await userApi.fetchMasterInfo() userStore.setUser(userData) await router.push({ name: DASHBOARD_ROUTE }) }
I don't understand why the router is undefined everywhere, is there any way to fix this without passing the router as a parameter? (I want to completely encapsulate the checkUserAuth function)
I know I can fix it
const router = useRouter() onMounted(async () => { await checkUserAuth(router) }) export const checkUserAuth = async (router: Router) => { await router.push({ name: DASHBOARD_ROUTE }) }
But this is not a good solution
The API of useRouter must be called in setup, as mentioned in the official documentation. You can see this in https://router.vuejs.org/zh/api/#userouter (mentioned in zh documentation). Maybe you can write code like this:
and call it in settings:
hope it helps you.
Composable items should be used directly in settings unless their implementation allows other uses, which needs to be determined on a case-by-case basis.
Since checkUserAuth uses a composable, which makes it composable, if you need to use it within an installed hook, you need to return a function that allows this:
Alternatively,
checkUserAuth
composables should not be used.useUserStore
has no limitations inherent in composable items, anduseRouter
can be replaced with an import of a router instance.