vue.js 如何删除待办事项列表中的任务?

qybjjes1  于 2023-05-07  发布在  Vue.js
关注(0)|答案(2)|浏览(144)

我希望通过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;
  }
};
rsaldnfx

rsaldnfx1#

你需要传入id @click="deleteTask(task.id)"和in方法:

deleteTask(id) {
  this.$store.dispatch('deleteTask', id);
},
fkaflof6

fkaflof62#

您正在接收404,因为您正在呼叫https://dummyjson.com/todos/undefined
1 -您需要分派ID:

// Task.vue - line 26
  deleteTask(id) {
        this.$store.dispatch('deleteTask', id);
  },

2 -另外,调用“deleteTask”方法,其id为:

// Task.vue - line 10
  <button @click="() => deleteTask(task.id)" class="delete">Delete</button>

之后,您将调用https://dummyjson.com/todos/1

相关问题