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

Let's create a component that uses the parameters from this object. Create a new object in


your routes array:


const router = new VueRouter({
routes: [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:name',
component: User
}
],

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

The thing you'll notice that is different with this path is the colon preceding the name in the


path. This tells Vue-router that this part of the URL is dynamic, but the variable name for
that section is name.


Now create a new component called User, and create a template for it. For this example,


our template will be inline and we will be using the ES2015 template syntax. This uses


backticks and allows the passing of variables and new lines directly into the template
without the need to escape them:


const User = {
template: `<h1>Hello {{ $route.params.name }}</h1>`
};

The variable being output within the template is from the global router instance and is the


name variable within the parameters object. The variable name references the


variable preceded by the colon in the route path, within the routes array. Within the


component template, we can also omit this variable from the $route.

Free download pdf