0👍
I’ve updated your code.
Here are the major things that changed:
- The
selected
data property is changed to object so that it can handle multiple arrays of selected toppings based on the category. - A
watcher
for thecategories
is added which will react everytime the category is changed. So for example, if you added a new category into your store, theselected
data property will add new array entries for each new category that was added. - We used
this.$set()
to add new entry to yourselected
object. This is crucial for keeping everything reactive, specially to object properties or arrays that are dynamically added. - We updated the
v-model
mapping for the checkbox intov-model="selected[category.name]"
- Lastly, we can now loop the
selected
to retrieve the selected toppings for each category
like this:
this.selected.forEach((selected, category_name) => {
this.item.toppings.push(selected);
});
See the fully updated code below:
export default {
name: "AddToppings",
props: ['item', 'quantity'],
data() {
return {
selected: {}
}
},
created() {
},
computed: {
categories() {
return this.$store.state.cat_toppings;
}
},
watch: {
categories: {
immediate: true,
handler(categories) {
categories.forEach((category) => {
if (this.selected[category.name] == undefined) {
this.$set(this.selected, category.name, []);
}
})
}
}
},
methods: {
cancelCatDelete() {
$('#addToppings').modal('hide')
},
closeForm() {
//console.log('cart', this.item);
$('#addToppings').modal('hide');
this.selected.forEach((selected, category_name) => {
this.item.toppings.push(selected);
});
this.$store.dispatch('addItemToCart', this.item);
this.selected = [];
this.$emit('form_closed');
}
}
}
<div v-for="n in Number(quantity)">
<button class="btn btn-primary" type="button" data-toggle="collapse" :data-target="'#collapse' +n" aria-expanded="false" aria- controls="collapseExample">
Add Toppings for <b>Pizza - {{n}}</b>
</button>
<div class="collapse.show" :id="'#collapse' +n">
<div class="card card-body">
<div class="row">
<div v-for="category in categories" class="col">
<table>
<tr>
<th>
<h4><b>{{category.name}}</b></h4>
</th>
</tr>
<tr v-for="name in category.topping_items">
<td>
<input type="checkbox" v-model="selected[category.name]" :value="name.item
+ '-pizza-' + n " :id="name.id + n" />
<label :class="{bold_name: name.double_price}" :for="name.id + n">{{name.item}}</label>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="align-content-center">
<button @click="closeForm">Add Selected Toppings</button>
</div>
- [Vuejs]-Vue.js testing toBe() method return only object when expected 'string' etc
- [Vuejs]-Vuejs: Use stored data withing nuxt pages
Source:stackexchange.com