Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Building an E-Commerce Store - Adding a Checkout Chapter 11

Updating the Add to basket button when adding an item


As a usability improvement to our shop, we are going to update the Add to basket button


when a user clicks it. This will change to Added to your basket and apply a class for a set
period of time, for example, two seconds, before returning to its previous state. The CSS


class will allow you to style the button differently—for example, changing the background


to green or transforming it slightly.


This will be achieved by using a data property on the component—setting it to true and


false as the item gets added. The CSS class and text will use this property to determine


what to show and a setTimeout JavaScript function will change the state of the property.


Open the ProductPage component and add a new key to the data object titled


addedToBasket. Set this to false by default:


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

Update the button text to allow for this variation. As there is already a ternary if, within


this, we are going to nest them with another one. This could be abstracted into a method if


desired.


Replace the Add to basket condition in your button with an additional ternary operator,


dependent on whether the addedToBasket variable is true. We can also add a conditional


class based on this property:


<button
@click="addToBasket()"
:class="(addedToBasket)? 'isAdded' : ''"
:disabled="!variation.quantity"
>
{{
(variation.quantity)?
((addedToBasket)? 'Added to your basket' : 'Add to basket') :
'Out of stock'
Free download pdf