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

path: '/about',
component: About
}
]
});

Each route object contains a path and component key. The path is a string of the URL that


you want to load the component on. Vue-router serves up components based on a first-


come-first-served basis. For example, if there are several routes with the same path, the first
one encountered is used. Ensure each route has the beginning slash—this tells the router it


is a root page and not a sub-page, we will cover sub-pages later on in the chapter.


Press save and view your app in the browser. You should be presented with the content of


the Home template component. If you observe the URL, you will notice that on page load a


hash and forward slash (#/) is appended to the path. This is the router creating a method


for browsing the components and utilizing the address bar. If you change this to the path of
your second route, #/about, you will see the contents of the About component.


Vue-router is also able to use the JavaScript history API to create prettier URLs. For


example, yourdomain.com/index.html#about would


become yourdomain.com/about. This is activated by adding mode: 'history' to your


VueRouter instance:


const router = new VueRouter({
mode: 'history',

routes: [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
}
]
});

However, it also requires some server configuration to catch all requests and redirect them


to your index.html page, which is beyond the scope of this book but is fully outlined in


the Vue-router documentation.

Free download pdf