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

(singke) #1
Single Page Applications Chapter 15

How it works...


There are two main parts of the code that contribute to creating the routes for the different


dishes.


First, we registered a generic route using the colon syntax and assigned a name to it, which
is as follows code:


{ path: '/menu/:id', name: 'menu', component: Menu }

This means that we can have a URL that ends in /menu/82, and the Menu component will


be displayed with the $route.params.id variable set to 82. So, the following line


should be changed as per the following:


<img :src="'http://lorempixel.com/200/200/food/' + $route.params.id">

The preceding line will be replaced by the following line in the rendered DOM:


<img src="'http://lorempixel.com/200/200/food/82">

Never mind the fact that there is no such image in real life.


Note that we also gave a name to this route. This is not strictly necessary, but it enabled us
to write the second main part of the code, as shown:


<router-link :to="{ name: 'menu', params: { id: i } }">
Menu {{i}}
</router-link>

Instead of writing a string, we can pass an object to the to prop and specify the params. In


our case, the param is given by the v-for wrapping. This means that, for example, at


the fourth cycle of the v-for:


<router-link :to="{ name: 'menu', params: { id: 4} }">
Menu 4
</router-link>

This will result in the DOM as follows:


<a href="#/menu/4" class="">Menu 4</a>
Free download pdf