I have a table where the row elements are all populated by child components. There is a checkbox in each of these child components. Now I want to get all checked checkboxes at once. I could use prefs emit as two way binding and update an array or object on the parent but I am wondering if there is better way for this.
Here a short example for the template part:
<table>
<thead>
<tr>
<th> Check </th>
<th> Title </th>
</tr>
</thead>
<list-tbody v-for="element in elements" :element="element"> </list-tbody>
</table>
and this is the child component
<tbody>
<tr>
<td>
<input type="checkbox">
</td>
<td> {{element.title}} </td>
</tr>
</tbody>
As mentioned in the comments you could handle this in two ways:
You prefer the second because you're not using Vuex and that's OK.
Once you're having the data "linked" between child component and parent you can use a filter method to only show the selected elements.
Please have a look at the demo below or the fiddle from my comment.
You should really stick to emitting values to maintain separation of your components. That being said, you can do the following if you really wanted to grab the data all at once:
First, you'll need a data attribute in your child component that your checkbox uses with
v-model
. For the sake of this example, let's just call itcheckbox_value
. Once you've done that, you can do something like the following in your parent component method:Of course, I wouldn't encourage you to do something like this, but you'll have to make that judgement call.
Note: The above will return values only. You could push object key/value pairs instead!