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

The next step is to disable the delivery fields if the checkbox is checked. This can be done by


activating the disabled HTML attribute based on the checkbox result. In a similar way to


how we disabled the "Add to cart" button on the product page, bind the disabled attribute


on the delivery fields to the sameAddress variable:


<fieldset>
<h2>Delivery Details</h2>
<label for="deliveryName">Name:</label>
<input type="text" id="deliveryName" v-model="delivery.name"
:disabled="sameAddress">
<label for="deliveryAddress">Address:</label>
<input type="text" id="deliveryAddress" v-model="delivery.address"
:disabled="sameAddress">
<label for="deliveryZipcode">Post code/Zip code:</label>
<input type="text" id="deliveryZipcode" v-model="delivery.zipcode"
:disabled="sameAddress">
</fieldset>

Checking the box will now deactivate the fields - making the user unable to enter any data.
The next step is to replicate the data across the two sections. As our data objects are the


same structure, we can create a watch function to set the delivery object to the same as


the billing object when the checkbox is checked.


Create a new watch object and function for the sameAddress variable. If it is true, set the


delivery object to the same as the billing one:


watch: {
sameAddress() {
if(this.sameAddress) {
this.delivery = this.billing;
}
}
}

With the watch function added, we can enter data into the billing address, check the box,


and the delivery address gets populated. The best thing about this is that they now stay in


sync, so if you update the billing address, the delivery address updates on the fly. The
problem arises when you uncheck the box and edit the billing address—the delivery


address still updates. This is because we have bound the objects together.

Free download pdf