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

<button @click="addToBasket()" :disabled="!variation.quantity">
{{ (variation.quantity)? 'Add to basket' : 'Out of stock' }}
</button>
</div>

By removing elements when they are not needed, we now have a less cluttered interface.


Updating the product details when switching URLs


While navigating through the different product URLs to check variations, you may have
noticed that clicking back and forward doesn't update the product data on the page.


This is because Vue-router realizes the same component is being used between the pages,


and so, rather than destroying and creating a new instance, it reuses the component. The


downside to this is that the data does not get updated; we need to trigger a function to


include the new product data. The upside is that the code is more efficient.


To tell Vue to retrieve the new data, we need to create a watch function; instead of


watching a variable, we are going to watch the $route variable. When this gets updated,


we can load new data.


Create a new variable in the data instance of slug, and set the default to be the route


parameter. Update the product computed function to use this variable instead of the route:


const ProductPage = {
name: 'ProductPage',

template: `...`,

components: {
PageNotFound
},
data() {
return {
slug: this.$route.params.slug,
productNotFound: false,
image: false,
variation: false
}
},

computed: {
Free download pdf