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

This now gives us a new HTML element to use in the form of . Add


this element to your template after the existing

. As our templates need a single root


element, wrap both of them in an extra container:


const ProductPage = {
name: 'ProductPage',

template: `<div>
<div v-if="product"><h1>{{ product.title }}</h1></div>
<page-not-found></page-not-found>
</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;
}
}
};

Viewing this in the browser will render the 404 page template and, once the data has


loaded, the product title above that. We now need to update the component to only show


the PageNotFound component when there is no data to show. We could use the existing


product variable with a v-if attribute and, if false, show the error message like so:


<page-not-found v-if="!product"></page-not-found>

However, this would mean that if the user visited the product page without the product


data loading yet, they would see a flash of the 404 information before being replaced with
the product information. This isn't a very good user experience, so we should only show


the error if we are sure the product data has loaded and that there isn't a matching item.

Free download pdf