Dynamic Route Matching in Vue.js 3 SPA
Implementing dynamic routing in a Vue.js 3 application to handle parameterized URLs, with a focus on fetching data based on route parameters.
import { createRouter, createWebHistory } from 'vue-router';
// Define route components
const User = { /* ... */ };
// Create the router instance
const router = createRouter({
history: createWebHistory(),
routes: [
// Dynamically match routes to their components
{ path: '/user/:id', component: User }
]
});
export default router;
This code creates a Vue Router instance with dynamic route matching. It imports the necessary functions from 'vue-router' and defines a User component. The '/user/:id' route will match any path following the '/user/' pattern and pass the 'id' as a route parameter to the User component.
import { ref } from 'vue';
import { useRoute } from 'vue-router';
export default {
setup() {
// Use the useRoute composable to access the current route
const route = useRoute();
const userData = ref({});
// A method to fetch user data based on the route parameter
async function fetchUserData() {
const userId = route.params.id;
// Fetch user data from an API or other source based on the userId
// userData.value = await fetchUserFromAPI(userId);
}
// Call fetchUserData when the component is created or when the route changes
watch(() => route.params.id, (newId, oldId) => {
if (newId !== oldId) {
fetchUserData();
}
}, { immediate: true });
return { userData };
}
};
This code snippet is part of a Vue component that uses the 'useRoute' composable to access route parameters in a setup function, which is part of Vue 3's Composition API. It defines a ref to store user data and a method to fetch user data based on the route parameter 'id'. It also sets up a watch effect to call 'fetchUserData' whenever the route's 'id' parameter changes to ensure the component always displays up-to-date information.