Vue Router & Navigation
Vue Router maps URL paths to component views, enabling client-side routing in single-page applications without triggering full page reloads.
1 Router Views, parameters and routes mapping
Configuring client-side routing requires setting up routing mappings:
- router-link: Sells navigation links, avoiding full browser refreshes:
<router-link to="/about">. - router-view: A placeholder viewport component telling Vue Router where to render the matched component route.
- Dynamic Routes: Map URLs with parameter variables:
path: '/user/:id'. Access these parameters inside scripts using theuseRoute()hook.
2 Defining Vue Routing Configuration
Let's check how to initialize a routing setup:
TypeScript — Router Setup
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from './views/HomeView.vue';
import ProfileView from './views/ProfileView.vue';
const routes = [
{ path: '/', component: HomeView },
{ path: '/profile/:id', component: ProfileView }, // dynamic param route
{ path: '/:pathMatch(.*)*', redirect: '/' } // fallback route
];
export const router = createRouter({
history: createWebHistory(),
routes
});
Read parameters dynamically inside components using the useRoute hook:
TypeScript — Reading Params Hook
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
// Read route parameter id
const userId = route.params.id;
</script>
3 Code Challenge
Challenge: Write a navbar component with dynamic links using
<router-link>. Apply active styling class highlights using the active-class attribute property.