const listTbodyVuex = {
props: ['element'],
template: `
<tbody>
<tr>
<td>
<input type="checkbox" @click="selected">
</td>
<td> {{element.title}} </td>
</tr>
</tbody>
`,
methods: {
...Vuex.mapMutations(['changeSelection']),
selected(evt) {
this.changeSelection({
id: this.element.id, selected: evt.target.checked
});
}
}
}
const listTbodyEvents = {
props: ['element'],
template: `
<tbody>
<tr>
<td>
<input type="checkbox" @click="selected">
</td>
<td> {{element.title}} </td>
</tr>
</tbody>
`,
methods: {
selected(evt) {
console.log('clicked', evt.target.checked)
this.$emit('selected', {
element: this.element,
newSelection: evt.target.checked
})
}
}
}
const store = new Vuex.Store({
state: {
elements: [
{
id: 0,
title: 'first',
selected: false
},
{
id: 1,
title: 'second',
selected: false
},
{
id: 2,
title: 'third',
selected: false
}
]
},
mutations: {
changeSelection(state, {id, selected}) {
let element = state.elements
.filter((element) => element.id === id)[0];
element.selected = selected;
Vue.set(state.elements, element.id, element);
}
}
})
new Vue({
el: '#app',
store,
data() {
return {
elements: [
{
id: 0,
title: 'first',
selected: false
},
{
id: 1,
title: 'second',
selected: false
},
{
id: 2,
title: 'third',
selected: false
}
]
}
},
computed: {
...Vuex.mapState({
vuexElements: (state) => state.elements
})
},
components: {
listTbodyEvents,
listTbodyVuex
},
methods: {
updateElement(data) {
let element = this.elements
.filter((element) => element.id === data.element.id)[0];
element.selected = data.newSelection;
},
filterSelected(data) {
return data.filter((item) => item.selected);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.0/vuex.js"></script>
<div id="app">
<h1>Example with vuex</h1>
<table>
<thead>
<tr>
<th> Check </th>
<th> Title </th>
</tr>
</thead>
<list-tbody-vuex v-for="element in elements" :element="element" :key="element.id"> </list-tbody-vuex>
</table>
<pre>only selected: {{filterSelected(vuexElements)}}</pre>
<pre>{{vuexElements}}</pre>
<hr/>
<h1>Example with events</h1>
<table>
<thead>
<tr>
<th> Check </th>
<th> Title </th>
</tr>
</thead>
<list-tbody-events v-for="element in elements" :element="element" :key="element.id" @selected="updateElement"> </list-tbody-events>
</table>
<pre>only selected: {{filterSelected(elements)}}</pre>
<pre>{{elements}}</pre>
</div>