Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Introducing Vue-Router and Loading URL-Based Components Chapter 8

Add the name key to your routes, as shown in the following example:


const router = new VueRouter({
routes: [
{
path: '/',
component: Home
},
{
path: '/about',
component: About,
children: [
{
name: 'contact',
path: 'contact',
component: AboutContact
},
{
name: 'food',
path: 'food',
component: AboutFood
}
]
},
{
path: '*',
component: PageNotFound
}
],

linkActiveClass: 'active',
linkExactActiveClass: 'current'
});

You can now use that name when creating your router-link component, like so:


<router-link :to="{name: 'food'}">Food</router-link>

Note the colon before the to attribute. This ensures the contents are parsed as an object, not


a literal string. Another advantage of using named routes is being able to pass specific
attributes to our dynamic paths. Using the example from earlier in this chapter, we can


build the URL in a programmatic way, abstracting the data away from the path
construction. This is where named routes really come into their own. Say we had the


following path:


{ name: 'user', path: '/:name/user/:emotion', component: User }
Free download pdf