router-link
router-link creates navigation links that change the URL without reloading the page.
In this page:
Syntax
<router-link to="/path">link text</router-link>
<router-link :to="{ name: 'route-name' }">link text</router-link>
router-link
Use <router-link to="/about"> instead of <a href>. It renders an anchor, adds active classes automatically, and intercepts clicks for client-side navigation. The to prop accepts a path string or an object with name and params.
Note:
The router-link-active class marks links matching the current route.
Example: router-link
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
</head>
<body>
<div id="app">
<nav>
<router-link to="/">Home</router-link> |
<router-link :to="{ name: 'about' }">About</router-link>
</nav>
<router-view></router-view>
</div>
<script>
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{ path: "/", component: { template: "<p>Home content</p>" } },
{ path: "/about", name: "about", component: { template: "<p>About content</p>" } },
],
});
Vue.createApp({}).use(router).mount("#app");
router.isReady().then(async () => {
document.querySelectorAll("a")[1].click();
await router.isReady(); await Vue.nextTick(); await new Promise((r) => setTimeout(r, 30));
console.log("path:", router.currentRoute.value.path, "| view:", document.querySelector("p").textContent);
});
</script>
</body>
</html>
<!-- Output:
Rendered: Home | AboutAbout content
console: path: /about | view: About content
-->
Live Example
Related Topics
Common Mistakes
- Using plain anchors that reload the page
- Forgetting the to prop
- Hard-coding paths instead of names
Chapter Summary
- router-link navigates client-side
- to accepts a path or object
- Active classes are added automatically
- Avoids full page reloads
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: