How to Watch Route With Vue js 3 Composition API
When you are working on a blog project with Vue js 3 Composition API and you want to display articles based on the category selected by the user, and the category is retrieved using routes you must watch the route to get articles dynamically.
How we can do that ?
All you need to do is to add the watch function and give it the fetchPostsByCategory function with the route params, so it will trigger the function every time the route changes.
import { useRoute } from 'vue-router';
import { onMounted, watch } from 'vue';
const route = useRoute();
//get posts by category
onMounted(() => fetchPostsByCategory(route.params.categoryId));
watch(route, () => fetchPostsByCategory(route.params.categoryId));