We recently migrated from Vue 2 to Vue 3 and updated Vue Router to version 4. However, we’re facing an issue where useRoute() and useRouter() are always undefined in our shared components.
Project Structure:
Shared Folder Project: Contains shared Vue components using the route.
Other Folders/Apps: Use these shared components. Routes are defined here, and the components within these apps have access to useRoute() and useRouter().
The issue arises in the shared folder, where the components don’t have access to the route or router. The shared folder is added as a dependency in our other projects.
Things We’ve Tried:
Github Copilot suggested the following, which we have already tried:
Component Isolation:
Ensure shared components are used within a component that is wrapped with the router context.
Lazy Loading or Dynamic Imports:
Verify that dynamically/lazily imported components are rendered within the router context.
Using Shared Components in Non-Routed Contexts:
Ensure shared components are always used in a routed context.
Proper Router Setup:
Ensure Vue Router is properly set up and passed to the Vue app (app.use(router)), and the components using useRoute() or useRouter() are part of the router-managed app.
Proposed Solutions:
Wrap the Shared Components:
Ensure shared components are used in a routed component.
Prop Drilling:
Pass route information (e.g., route params or router methods) as props from a parent component that has router access.
Ensure Proper Context:
Double-check that shared components are always used within the Vue Router context.
Despite these attempts, the issue persists. We considered using getCurrentInstance() as a temporary workaround, but prefer the recommended approach for accessing the route/router in Vue Router 4 instead of passing the route and router to all our components as params.
Have you encountered a similar issue?
How did you resolve it?
Is there a specific Webpack configuration that could affect this?
We’re not using Vite yet, but suspect the shared folder issue would persist even with Vite.
Any insights or suggestions would be greatly appreciated!
1