Reputation: 2354
I'm just getting started with vue.js and I'm having a hard time figuring out how to attach models to form elements. I have a form with "addons" that looks like this:
<div id="example">
<input type="checkbox" name="option1" value="10" v-model="addons">
<select name="option2" v-model="addons">
<option value="5" />
<option value="10 />
<option value="15" />
</select>
<input type="radio" name="option3" value="10" v-model="addons">
<input type="radio" name="option3" value="20" v-model="addons">
<div>{{total}}</div>
</div>
I'm trying to get the sum of all the selected addons. This means that if the user checks the checkbox, selects the second option, and selects the first radio button, the last div should display "30". The form is being generated on the server and so I have no easy way of knowing which type of controls will be present.
This is what I have so far on the javascript side, but it's not working:
new Vue({
el: '#example',
data: {
addons: []
},
computed: {
total: function() {
return this.addons.reduce(function(sum, addon) {
return sum + addon;
}, 0);
}
}
})
What am I missing?
Upvotes: 0
Views: 6407
Reputation: 25221
You can bind multiple checkboxes to the same variable, and it will create an array. However, you can't model multiple types of inputs to the same variable. You'd need to bind the select to a different variable and the radio buttons to a different variable, then sum those.
Fiddle: https://jsfiddle.net/69dty5a1/
new Vue({
el: '#example',
data: {
addons: 10,
select:5,
radio:10
},
computed: {
total: function() {
return parseInt(this.addons) + parseInt(this.radio) + parseInt(this.select);
}
}
})
Upvotes: 1