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

Now we have created our Hello.vue component, let's create the second World.vue like


so:


// World.vue
<template>
<div>
<h1>World</h1>
<router-link to="/hello">Back</router-link>
</div>
</template>

<script>
export default {};
</script>

We can then initialize our router as we usually do, inside main.js:


import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

The main difference has to do with the way in which to import our components. This


requires the use of the syntax-dynamic-import Babel plugin. Install it into your project


by running the following in your Terminal:


$ npm install --save-dev babel-plugin-syntax-dynamic-import

We can then update .babelrc to use the new plugin:


{
"presets": [["env", { "modules": false }], "stage-3"],
"plugins": ["syntax-dynamic-import"]
}

Finally, this allows us to import our components asynchronously, like this:


const Hello = () => import('./components/Hello');
const World = () => import('./components/World');

We can then define our routes and initialize the router, this time referencing the


asynchronous import:


const routes = [
{ path: '/', redirect: '/hello' },
{ path: '/hello', component: Hello },
{ path: '/World', component: World },
];
Free download pdf