I'm building a Vue.js app where the user can choose the payment method clicking on 3 buttons (Credit card, Paypal, Iban). Each ones call the method setPayment(type)
where type
is the choosen payment method (cc, paypal, iban).
Below is the code. Look at the method setPayment(type)
: is there a way to avoid to set to false
everytime the other 2 payment. The code is working but I think it's too much verbose and dirty.
Or maybe there is another better way to do the whole thing?
new Vue({
el: "#app",
//
// Data
//
data: {
payment: {
cc: true,
paypal: false,
iban: false
}
},
//
// Methods
//
methods: {
// Set payment
setPayment: function(type) {
if (type == 'cc'){
this.payment.cc = true;
this.payment.paypal = false;
this.payment.iban = false;
}
if (type == 'paypal'){
this.payment.cc = false;
this.payment.paypal = true;
this.payment.iban = false;
}
if (type == 'iban'){
this.payment.cc = false;
this.payment.paypal = false;
this.payment.iban = true;
}
}
}
});
You could turn payment
into a computed property and use a selectedPayment
type.
payment(){
return {
cc: this.selectedPayment === 'cc',
paypal: this.selectedPayment === 'paypal',
iban: this.selectedPayment === 'iban'
}
}
Example.
console.clear() new Vue({ el: "#app", data: { selectedPayment: null, }, computed: { payment(){ return { cc: this.selectedPayment === 'cc', paypal: this.selectedPayment === 'paypal', iban: this.selectedPayment === 'iban' } } }, methods:{ onSelectPayment(type){ this.selectedPayment = type // do other stuff. If you need the payment, it is available // as this.payment } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script> <div id="app"> Payment: {{payment}} <hr> <button @click="onSelectPayment('cc')">CC</button> <button @click="onSelectPayment('paypal')">PayPal</button> <button @click="onSelectPayment('iban')">Iban</button> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.