The `router-link` Component in Vue
The router-link component
creates an <a> tag that's configured to work correctly with
Vue router. For example, given the
below Vue code:
const router = new VueRouter({
routes: [
{ path: '/home', component: { template: '<h1>Home</h1>' } },
{ path: '/about', component: { template: '<h1>About Us</h1>' } }
]
});
const app = new Vue({
router,
template: `
<div id="rendered-content">
<div>
<router-link to="/home">Home</router-link>
<router-link to="/about">About Us</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
`
}).$mount('#content');
Vue will render the below HTML. Note that <router-link> becomes
a plain-old <a> tag.
<div>
<a href="#/home" class="">Home</a>
<a href="#/about" class="">About Us</a>
</div>
<div><!----></div>
With the above example, you can write your own <a> tags instead
of going through <router-link>, but then you would need to
do extra work to support named routes and HTML5 mode.
Custom Tags
The router-link component supports a neat tag prop
that lets you specify a custom tag to use for navigation, as
opposed to the default <a>. For example, here's how you
can use buttons for navigation instead of <a> tags:
const app = new Vue({
router,
template: `
<div id="rendered-content">
<div>
<router-link to="/home" tag="button">Home</router-link>
<router-link to="/about" tag="button">About Us</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
`
}).$mount('#content');
Vue would render the below HTML:
<div>
<button class="">Home</button>
<button class="">About Us</button>
</div>
<div><!----></div>
Looks like the buttons don't do anything, but Vue Router registered event handlers to make clicking on the buttons trigger navigation as shown below.