How to Use router-link in Vue for Navigation
Use the
router-link component in Vue to create navigation links that connect to different routes defined in Vue Router. Set the to attribute to the target route path or name, and Vue Router will handle the navigation without reloading the page.Syntax
The router-link component creates a clickable link that navigates to a route defined in Vue Router. The to attribute specifies the destination path or named route. You can also customize the link with props like replace to avoid adding a new history entry.
vue
<router-link to="/home">Go to Home</router-link>Output
A clickable link labeled 'Go to Home' that navigates to the '/home' route without reloading the page.
Example
This example shows a simple Vue app with Vue Router. The router-link components let users navigate between Home and About pages smoothly.
vue
import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; const Home = { template: '<div><h2>Home Page</h2><p>Welcome to the Home page.</p></div>' }; const About = { template: '<div><h2>About Page</h2><p>Learn more about us here.</p></div>' }; const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = createRouter({ history: createWebHistory(), routes }); const App = { template: ` <div> <nav> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </nav> <router-view></router-view> </div> ` }; createApp(App).use(router).mount('#app');
Output
A page with navigation links 'Home' and 'About'. Clicking links changes the displayed page content below without reloading.
Common Pitfalls
- Forgetting to use
router-linkand using a normal<a>tag causes full page reloads. - Not setting up Vue Router properly means
router-linkwon't work. - Using incorrect paths in
toleads to navigation errors or blank pages.
vue
/* Wrong: causes full page reload */ <a href="/about">About</a> /* Right: uses Vue Router navigation */ <router-link to="/about">About</router-link>
Output
The first link reloads the entire page; the second link changes the page content smoothly without reload.
Quick Reference
| Prop | Description | Example |
|---|---|---|
| to | Target route path or name | |
| replace | Navigate without adding history entry | |
| custom | Use scoped slot for custom rendering | |
| active-class | CSS class when link is active |
Key Takeaways
Use with the 'to' attribute to navigate between routes without page reloads.
Always set up Vue Router correctly for to work.
Avoid using normal tags for internal navigation to prevent full page reloads.
Customize with props like 'replace' and 'active-class' for better control.
Use to display the matched route component content.