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

},

methods: {
...
}
};

Update the addToBasket method to use the variation variable of the ProductPage


component and not rely on a parameter:


addToBasket() {
alert(`Added to basket: ${this.product.title} -
${this.variantTitle(this.variation)}`);
}

Try clicking the Add to basket button – it should add the first variation, regardless of what


is selected in the dropdown. To update the variable on change, we can bind the


variations variable to the select box – in the same way, that we did our textbox filtering


at the beginning of this book.


Add a v-model attribute to the select element. We will also need to tell Vue what to bind


to this variable when selecting. By default, it will do the contents of the


currently our custom variant title. However, we want to bind the whole variation object.


Add a :value property to the


<div class="variations">
<select v-model="variation">
<option
v-for="variation in product.variationProducts"
:key="variation.barcode"
:value="variation"
v-html="variantTitle(variation)"
></option>
</select>

<button @click="addToBasket()">Add to basket</button>
</div>

Changing the select box and clicking the Add to basket button will now produce the
correct variation. This method gives us much more flexibility over displaying the variations


in a table.

Free download pdf