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

(singke) #1
Using Vue-Router Dynamic Routes to Load Data Chapter 9

Page Not Found


With our first route created, we should also create our PageNotFound route, to catch any


URLs that are non-existent. We can also redirect to this page when there is no product that


matches.


We're going to create the PageNotFound component in a slightly different way than we did


before. Rather than having the component on *, we're going to create a /404 path as a


named route. This allows us to alias and redirect several different routes as required.


Add a new object to the routes array, with /404 as the path, the PageNotFound


component as the specified component. Add a name to your route, so we can utilize if
required, and lastly, add an alias attribute, which contains our global, catchall route.


Don't forget to put this at the end of the routes array – to catch any previously unspecified


route. When adding new routes, always remember to put them before the PageNotFound


route:


const router = new VueRouter({
routes: [
{
path: '/product/:slug',
component: ProductPage
},

{
path: '/404',
alias: '*',
component: PageNotFound
}
]
});

Add a template to your PageNotFound component. For now, give it some basic content –


we can improve it later, once we have the rest of our app set out:


const PageNotFound = {
name: 'PageNotFound',
template: `<div>
<h1>404 Page Not Found</h1>
<p>Head back to the <router-link to="/">home page</router-link> and
start again.</p>
</div>`
};
Free download pdf