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

(singke) #1
Vue Router Patterns Chapter 20

Creating routes


We can then define two small components inside our main.js file that simply have a


template that shows h1 with some text inside:


const Hello = { template: `<h1>Hello</h1>` };
const World = { template: `<h1>World</h1>`};

Then, in order to display these components on screen at particular URLs (such as /hello


and /world), we can define routes inside our application:


const routes = [
{ path: '/hello', component: Hello },
{ path: '/world', component: World }
];

Now that we've defined what components we want to use as well as the routes inside of
our application, we'll need to create a new instance of VueRouter and pass along the


routes.


Although we've used Vue.use(VueRouter), we still need to create a new instance of


VueRouter and initialize our routes. This is because merely registering VueRouter as a


plugin gives us access to the router option within our Vue instance(s):


const router = new VueRouter({
routes
});

We then need to pass the router to our root Vue instance:


new Vue({
el: '#app',
router,
render: h => h(App)
});

Finally, to display our routed components inside of our App.vue component, we need to


add the router-view component inside the template:


<template>
<div id="app">
<router-view/>
</div>
</template>
Free download pdf