user1592380
user1592380

Reputation: 36227

Mutiple checkboxes, bound to the same Array in Vue JS

I'm starting out with vuejs and a vue grid at https://jsfiddle.net/kc11/7fqgavvq/

I want to display the checked row objects in the:

    <pre> {{ selected| json}} </pre>

area of code,

as in the documentation at http://vuejs.org/guide/forms.html#Checkbox in the "Mutiple checkboxes, bound to the same Array:" example

As you can see when I check 1 checkbox, all are selected. Why is this happening? How can I fix this?

Upvotes: 0

Views: 3740

Answers (2)

pespantelis
pespantelis

Reputation: 15382

You should add the selected key to the component's data, not to the main instance of vue.

https://jsfiddle.net/7fqgavvq/4/

Upvotes: 1

nils
nils

Reputation: 27174

You made a few wrong assumptions in your code (mainly in respect to the scope).

You have your selected array in your main instance, instead of the demo-grid component, where you have your checkboxes:

var demo = new Vue({
    el: '#demo',
    data: {
        searchQuery: '',
        gridColumns: ['name', 'power'],
        gridData: [
            {name: 'Chuck Norris', power: Infinity},
            {name: 'Bruce Lee', power: 9000},
            {name: 'Jackie Chan', power: 7000},
            {name: 'Jet Li', power: 8000}
        ],
        selected: [] // <- This one
    }
})

And there is no selectAll method defined on your demo-grid component either, even though you reference it in your template:

<input @click="selectAll" type="checkbox" v-model="selected" id="{{ entry.name }}" value="{{ entry.name }}"></td>

If you thus pass your selected property into your demo-grid, (and define it in the props), you should be fine:

        <demo-grid
            v-bind:data="gridData"
            v-bind:columns="gridColumns"
            v-bind:filter-key="searchQuery"
            v-bind:selected="selected"> <!-- here -->
        </demo-grid>

And define a selectAll method:

methods: {
    ...
    selectAll: function () {
       ...
    }

Here you can see a working example: https://jsfiddle.net/7fqgavvq/3/

Upvotes: 3

Related Questions