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

Add a new cell at the beginning of the table that passes the variation to a method titled


variantTitle():


<div class="variations">
<table>
<tr v-for="variation in product.variationProducts"
:key="variation.barcode">
<td>{{ variantTitle(variation) }}</td>
<td>{{ variation.quantity }}</td>
<td>\${{ variation.price }}</td>
<td><button>Add to basket</button></td>
</tr>
</table>
</div>

Create the new method within your methods object:


methods: {
updateImage(img) {
this.image = img;
},

variantTitle(variation) {
}
}

We now need to construct a string with the title of the variant, displaying all available
options. To do this, we are going to construct an array of each of the types and then join


them into a string.


Store the variants as a variable and create an empty array. We can now loop through the


keys available within the variants object and create a string to output. If you decide to


add HTML into the string, as shown in the following example, we will need to update our
template to output HTML instead of a raw string:


variantTitle(variation) {
let variants = variation.variant,
output = [];

for(let a in variants) {
output.push(`<b>${variants[a].name}:</b> ${variants[a].value}`);
}
}
Free download pdf