1

in my Vue component I have checkboxes with array of items set to checkbox value:

<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. 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 will [{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 will [{id: 5, ...}, {id: 8, ...}] )

I need that because I need check or uncheck whole group of checkboxes.

Is possible do that in Vue? I didn't find anything about it in docs. Thanks.

1 Answer 1

1

You can create a computed property that takes selected and returns the flattened array, so for example have the computed property 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>
Sign up to request clarification or add additional context in comments.

7 Comments

I was just about to paste this exact answer from my text editor. =(
@gillyhl thanks for answer, but where to use this property?
Check my updated answer, if you export your Vue component like that, it'll be like the answer, add a property called computed in the export, and define the computed property you want. See the docs for a better explaination vuejs.org/v2/guide/computed.html
@gillyhl Thanks but I know how to use computed properties, but I don't know where to use this flatSelected. I need hold updated selected field because I also have checkboxes which has values as single object not array of objects
Updated answer, I think this is what you need.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.