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 variations


With this particular dataset, each of our products contains at least one variation but can


contain several. This normally goes hand-in-hand with the number of images but does not
always correlate. Variations can be things such as color or size.


On our Product object, we have two keys which are going to help us display the


variations. These are variationTypes, which list the names of the variations such as size


and color, and variationProducts,which contains all of the variations. Each product


within the variationProducts object has a further object of variant, which lists all of


the changeable properties. For example, if a jacket came in two colors and each color had


three sizes, there would be six variationProducts, each with two variant properties.


Every product will contain at least one variation, although if there is only one variation, we
may need to consider the UX of the product page. We are going to display our product


variations in both a table and drop-down, so you can experience creating both elements.


Variations display table


Create a new container in your product template that will display the variations. Within


this container, we can create a table to display the different variations of the product. This
will be achieved with a v-for declaration. However, now that you are more familiar with


the functionality, we can introduce a new attribute.


Using a key with loops

When using loops in Vue, it is advised you use an extra attribute to identify each item,
:key. This helps Vue identify the elements of the array when re-ordering, sorting, or


filtering. An example of :key use would be:


<div v-for="item in items" :key="item.id">
{{ item.title }}
</div>

The key attribute should be a unique attribute of the item itself and not the index of the


item in the array, to help Vue identify the specific object. More information about using a


key with a loop is available in the official Vue documentation.


We'll be utilizing the key attribute when displaying our variations, but using the barcode


attribute.

Free download pdf