For some reason I can not find a working solution to toggle checkbox of an item from Vuex state array. I got it working to a point where I am able to display todo items, but whenever I try to commit and call a toggle mutation, it doesn't work as expected, nothing changes. If I set done = true, it works, but not toggling it. Any idea?
View:
<template>
<div >
<ul>
<li v-for="todo in $store.state.todos" :key="todo.id">
<input
type="checkbox"
v-model="todo.done"
@change="$store.commit('toggle', todo.id)"
/>
<h3>{{ todo.title }}</h3>
</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({});
</script>
<style></style>
State:
import { createStore } from 'vuex';
import Todo from '@/types/Todo';
import { State } from 'vue';
const store = createStore({
state() {
return {
todos: [] as Todo[],
};
},
mutations: {
add(state: State, todo: Todo) {
state.todos.push(todo);
},
toggle(state: State, todoId: number) {
const index = state.todos.findIndex((todo) => todo.id === todoId);
state.todos[index].done = !state.todos[index].done;
},
},
});
export default store;
CodePudding user response:
Try updating the memory reference of the todos array by cloning the state.todos
array and deconstructing the todo object.
state.todos = state.todos.map((todo) => ({...todo, done: todoId === todo.id ? !todo.done : todo.done }));