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

product() {
let product;

if(Object.keys(this.$store.state.products).length) {

product = this.$store.state.products[this.slug];

this.image = (product.images.length)? product.images[0] : false;
this.variation = product.variationProducts[0];

if(!product) {
this.productNotFound = true;
}
}

console.log(product);
return product;
}
},

watch: {
...
},

methods: {
...
}
};

We can now create a watch function, keeping an eye on the $route variable. When this


changes, we can update the slug variable, which in turn will update the data being


displayed.


When watching a route, the function has two parameters passed to it: to and from. The to


variable contains everything about the route we are going to, including parameters and the


component used. The from variable contains everything about the current route.


By updating the slug variable to the new parameter when the route changes, we are


forcing the component to redraw with new data from the store:


const ProductPage = {
name: 'ProductPage',

template: `<div>
<div v-if="product">
<div class="images" v-if="image">
<div class="main">
Free download pdf