我希望通过DELETE请求删除数组中的单个任务,但我遇到了404错误,即使url是正确的,并且我在方法中传递了userId,或者我应该使用id。同时,url数组同时具有userId和每个元素的id。
https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=pages%2Findex.vue,store%2Findex.js,components%2FTask.vue
// Child component
<template>
<div :class="{ task: task.completed }">
{{ task.todo }}
<button @click="deleteTask" class="delete">Delete</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: ['task'],
deleteTask(userId) {
this.$store.dispatch('deleteTask');
},
},
};
</script>
// Parent component
<template>
<Task v-for="task in tasks" :key="task.id" :task="task" />
</template>
<script>
export default {
data() {
return {
todo: '',
completed: false,
};
},
computed: {
tasks() {
return this.$store.state.tasks;
},
},
created() {
this.$store.dispatch('getTasks').then((data) => console.log(this.tasks));
},
methods: {
},
};
</script>
// Store
export const state = () => ({
tasks: [],
});
export const actions = {
async getTasks(context) {
const res = await fetch('https://dummyjson.com/todos');
if (res.ok) {
let result = await res.json();
context.commit('setTasks', result.todos);
}
return res.ok;
},
async deleteTask(context, id) {
const res = await fetch(`https://dummyjson.com/todos/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
});
if (res.ok) {
let result = await res.json();
context.dispatch('getTasks');
}
return res.ok;
}
};
export const mutations = {
setTasks(state, data) {
state.tasks = data;
}
};
2条答案
按热度按时间rsaldnfx1#
你需要传入id
@click="deleteTask(task.id)"
和in方法:fkaflof62#
您正在接收404,因为您正在呼叫
https://dummyjson.com/todos/undefined
1 -您需要分派ID:
2 -另外,调用“deleteTask”方法,其id为:
之后,您将调用
https://dummyjson.com/todos/1