Answer the question
In order to leave comments, you need to log in
Why is the whole array being passed and not an object?
I am writing Todo. I want to toggle the value of completed / not completed on click. But instead of an object, the entire array arrives in payload for some reason. What could be wrong? toggleTodo
App.vue Method
<template>
<div id="app">
<div v-for="todo in todos" :key="todo.id">
<div :class="{ 'red': todo.completed }">{{ todo.title }}</div>
<button @click="toggleTodo(todo)">Выполнено</button>
</div>
<input type="text" placeholder="Добавить todo" v-model="todo" />
<button @click="addTodo">Добавить todo</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
name: "App",
components: {},
data() {
return {
todo: "",
};
},
computed: {
...mapGetters({
todos: "GET_TODOS_FROM_STORE",
}),
},
methods: {
...mapActions(["fetchTodos", "toggleTodo"]),
addTodo() {
if (this.todo) {
this.$store.dispatch("addTodo", this.todo);
}
},
},
mounted() {
this.fetchTodos();
},
};
</script>
<style>
.red {
color: red;
}
</style>
import Vue from 'vue'
import axios from 'axios'
Vue.use(axios)
export default {
state: {
todos: [],
},
mutations: {
SET_TODOS(state, payload) {
state.todos = payload
},
ADD_TODO(state, payload) {
state.todos.push({
title: payload,
completed: false,
id: Math.floor(Math.random() * (300 - 10 + 1)) + 10,
userId: 1,
})
},
TOGGLE_TODO(payload) {
console.log(payload)
}
},
actions: {
fetchTodos({ commit }) {
axios.get('https://jsonplaceholder.typicode.com/todos/?_limit=10')
.then(response => response.data)
.then(todos => {
commit('SET_TODOS', todos)
})
},
addTodo({ commit }, payload) {
commit('ADD_TODO', payload)
},
toggleTodo({ commit }, payload) {
commit('TOGGLE_TODO', payload)
}
},
getters: {
GET_TODOS_FROM_STORE(state) {
return state.todos
}
}
}
Answer the question
In order to leave comments, you need to log in
In the mutation, the load is passed as the second argument, the first one is the storage state.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question