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

Viewing the app in the browser now, you will be presented with the title of the product –


once the data has loaded. This should only take a split second to load and should be
gracefully handled by our if statement.


Before proceeding with displaying all our product data, we need to handle the situation


where a product does not exist with the handle in the URL. Because our ProductPage


route is picking up anything after /product in the URL, the PageNotFound wildcard path


will not be able to be used – as it is our ProductPage component that is loading the data


and determining whether the product exists.


Catching products not found


In order to show the PageNotFound page when a product is not available, we are going to


load the component with our ProductPage component and display it conditionally.


To do this, we need to register the component so we can use it in our template. We need to
register it since our PageNotFound component currently lives as an object and not a Vue


component (for example, when we use Vue.component).


Add a components object to your ProductPage component and include PageNotFound:


const ProductPage = {
name: 'ProductPage',

template: `<div v-if="product"><h1>{{ product.title }}</h1></div>`,

components: {
PageNotFound
},

computed: {
product() {
let product;

if(Object.keys(this.$store.state.products).length) {
product = this.$store.state.products[this.$route.params.slug];
}

return product;
}
}
};
Free download pdf