我希望单击完成/未完成的单个任务按钮,使用Vuex
存储操作将完成的任务数据切换到相反状态。但是我收到了404错误。即使我正在传递子组件的任务id。或者我应该用突变来做?
https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=store%2Findex.js,components%2FTask.vue
// Child component
<template>
<div :class="{ task: task.completed }">
<p class="content">
{{ task.todo }}
</p>
<button @click="toggleTask">
{{ task.completed ? 'Undone' : 'Done' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: ['task'],
methods: {
toggleTask(id) {
this.$store.dispatch('toggleTask', id);
},
},
};
</script>
// Parent component
<template>
<Task v-for="task in tasks" :key="task.id" :task="task" />
</template>
<script>
export default {
data() {
return {
todo: '',
completed: false,
search: '',
};
},
computed: {
tasks() {
return this.$store.getters.getTasks(this.search);
},
},
mounted() {
this.$store.dispatch('getTasks').then((data) => console.log(this.tasks));
},
};
</script>
// Store
export const state = () => ({
tasks: [],
});
export const actions = {
async getTasks(context) {
const res = await fetch('https://dummyjson.com/todos/user/5');
if (res.ok) {
let result = await res.json();
context.commit('setTasks', result.todos);
}
return res.ok;
},
async toggleTask(context, id) {
const res = await fetch(`https://dummyjson.com/todos/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
// body: JSON.stringify(data),
});
if (res.ok) {
const tasks = (context.state.tasks.find(
(task) => task.id === id
).completed = !completed);
context.commit('setTask', id); // or should I commit to toggle task mutation and how can I do it ?
}
return res.ok;
},
};
export const mutations = {
setTasks(state, data) {
state.tasks = data;
},
toggleTask(state, id) {
state.tasks.find((task) => task.id === id).completed = !completed;
},
};
export const getters = {
},
};
2条答案
按热度按时间s3fp2yjn1#
首先,将
task
传递给方法:然后在Vuex中创建一个action,它将放置数据并提交mutation:
在末端突变:
vsdwdz232#
在单击处理程序中
id是一个事件对象。你需要在这里正确地传递id。下面应该工作