我正在Vue.js中构建比萨菜单应用程序。如果用户购买了3个相同大小的比萨饼,那么我需要显示他们想要为每个比萨饼添加的浇头。 问题是,当我单击“ pizza-3”的复选框时,它会跳到在“ pizza-1”上填充的支票。 由于某种原因,我无法获得彼此独立的浇头(复选框)集。我很难弄清楚这一点。请帮忙。
<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" :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>
<script>
export default {
name: "AddToppings",
props:['item', 'quantity'],
data(){
return{
selected:[]
}
},
created(){
},
computed:{
categories(){
return this.$store.state.cat_toppings;
}
},
methods:{
cancelCatDelete(){
$('#addToppings').modal('hide')
},
closeForm(){
//console.log('cart', this.item);
$('#addToppings').modal('hide');
this.item.toppings.push(this.selected);
this.$store.dispatch('addItemToCart', this.item);
this.selected = [];
this.$emit('form_closed');
}
}
}
答案 0 :(得分:0)
我已经更新了您的代码。
主要变化如下:
selected
数据属性已更改为object,以便它可以根据类别处理选定浇头的多个数组。watcher
的{{1}},每当类别更改时,它就会做出反应。因此,例如,如果您在商店中添加了新类别,则categories
数据属性将为添加的每个新类别添加新的数组条目。selected
向您的this.$set()
对象添加了新条目。这对于使所有内容保持反应性至关重要,尤其是对动态添加的对象属性或数组而言。selected
映射更新为v-model
v-model="selected[category.name]"
来检索每个类别的选定浇头像这样:
selected
请参阅下面的完整更新的代码:
this.selected.forEach((selected, category_name) => {
this.item.toppings.push(selected);
});
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');
}
}
}