[英]Add flat array to v-model by multiple checkboxes in VueJS
in my Vue component I have checkboxes with array of items set to checkbox value: 在我的Vue组件中,我有多个复选框,其中的项目数组设置为复选框值:
<div v-for="group in groups">
<input type="checkbox" v-model="selected" :value="group">
<template v-for="item in group">
<input type="checkbox" :value="item" v-model="selected">
</template>
</div>
My object groups is array of arrays looks like this: 我的对象组是数组的数组,看起来像这样:
let groups = [
[
{id:1, foo1: '...', foo2: '...'},
{id:2, foo1: '...', foo2: '...'}
],
[
{id:5, foo1: '...', foo2: '...'},
{id:8, foo1: '...', foo2: '...'}
],
];
So in template item
is represented by array. 因此在模板item
中由数组表示。 My goals is when I check checkbox, to model selected
will append flat array so for example when I check both checkboxes generated in loop, I will got in my selected
4 objects instead of 2 arrays of objects. 我的目标是当我选中复选框时,要selected
模型将追加平面数组,例如,当我选中循环生成的两个复选框时,我将获得selected
4个对象而不是2个对象数组。 (selected will [{id: 1, ...}, {id: 2, ...}, {id: 5, ...}, {id: 8, ...}]
) (将选择[{id: 1, ...}, {id: 2, ...}, {id: 5, ...}, {id: 8, ...}]
))
It also should works when some checkbox is unchecked. 当未选中某些复选框时,它也应该起作用。 For example when I uncheck first checkbox, I will got in selected
items of second checkbox instead of array. 例如,当我取消选中第一个复选框时,我将进入第二个复选框而不是数组的selected
项。 (selected will [{id: 5, ...}, {id: 8, ...}]
) (将选择[{id: 5, ...}, {id: 8, ...}]
)
I need that because I need check or uncheck whole group of checkboxes. 我需要这样做是因为我需要选中或取消选中整个复选框。
Is possible do that in Vue? Vue有可能吗? I didn't find anything about it in docs. 我没有在文档中找到任何有关它的信息。 Thanks. 谢谢。
You can create a computed property that takes selected and returns the flattened array, so for example have the computed property flatSelected: 您可以创建一个计算属性,该属性采用selected并返回展平的数组,例如,使计算属性flatSelected:
export default {
...,
computed: {
flatSelected () {
return this.selected.reduce((acc, cur) => [ ...acc, ...cur ], [])
}
}
}
Then in your template have the following 然后在您的模板中包含以下内容
<template>
<input v-for="item in itemsGroup" type="checkbox" :value="item" v-model="selected">
<input v-for="item in flatSelected" type="checkbox" :value="item" v-model="flatSelected">
</template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.