Episode 41 of 44

Adding Router Links

Use router-link for navigation — Vue's built-in component for creating links that trigger route changes without page reloads.

Adding Router Links

Instead of regular <a> tags, Vue Router provides the <router-link> component for navigation. It prevents full page reloads and triggers client-side route changes.

Basic Router Links

<nav>
    <router-link to="/">Home</router-link>
    <router-link to="/add">Add Blog</router-link>
</nav>

<router-link> renders an <a> tag by default. Clicking it changes the route without reloading the page.

Active Link Styling

<style>
.router-link-active {
    color: #42b883;
    font-weight: bold;
    border-bottom: 2px solid #42b883;
}
</style>

Vue automatically adds the router-link-active class to links that match the current route. You can style this class to highlight the active page.

Named Routes

// Router config
{ path: '/add', name: 'AddBlog', component: AddBlog }

// In template
<router-link :to="{ name: 'AddBlog' }">Add Blog</router-link>

Named routes let you reference routes by name instead of path — if the path changes later, the links still work.

Programmatic Navigation

methods: {
    goToHome() {
        this.$router.push('/');
    },
    goToAdd() {
        this.$router.push({ name: 'AddBlog' });
    }
}

Key Takeaways

  • <router-link to="/path"> creates navigation links without page reloads
  • router-link-active class is auto-applied to matching links for styling
  • Use named routes for maintainable links: :to="{ name: 'RouteName' }"
  • this.$router.push() navigates programmatically from methods