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

To combat this, we will create a new variable which will determine if the component


displays. Create a data function in the ProductPage component that returns an object with


a key of productNotFound, set to false. Add a v-if condition to the


element, checking against the new productNotFound variable:


const ProductPage = {
name: 'ProductPage',

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

components: {
PageNotFound
},
data() {
return {
productNotFound: false
}
},

computed: {
product() {
let product;

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

return product;
}
}
};

The last step is to set the variable to true if a product doesn't exist. As we only want to do


this once the data has loaded, add the code to the $store.state.products check. We are


already assigning the data to the product variable, so we can add a check to see if this


variable exists – if not, change the polarity of our productNotFound variable:


const ProductPage = {
name: 'ProductPage',

template: `<div>
<div v-if="product"><h1>{{ product.title }}</h1></div>
<page-not-found v-if="productNotFound"></page-not-found>
</div>`,
Free download pdf