为什么删除按钮删除所有项目而不是单个项目?

问题描述 投票:0回答:1

在列表中创建新的待办事项后,单击删除按钮后,所有新任务都会被删除,而不是单个任务。我希望只删除具有传递 ID 的专有者。

https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=pages%2Findex.vue,store%2Findex.js,components%2FTask.vue

// Child component

<template>
    <p class="content">
      {{ task.todo }}
    </p>
    <button @click="() => deleteTask(task.userId)" class="delete">
      Delete
    </button>
</template>

<script>
export default {
  props: ['task'],
  methods: {
    deleteTask(id) {
      this.$store.dispatch('deleteTask', id);
    },
  },
};
</script>

// Parent component

<template>
  <Task v-for="task in tasks" :key="task.id" :task="task" />
</template>

<script>
export default {
  computed: {
    tasks() {
      return this.$store.state.tasks;
    },
  },
  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 deleteTask(context, id) {
    const res = await fetch(`https://dummyjson.com/todos/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'appication/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;
  },
};

javascript arrays vue.js fetch vuex
1个回答
0
投票

如果我错了请纠正我,但不应该是您传递的是要删除的任务的

task ID
,而不是
user ID
?

<button @click="() => deleteTask(task.id)" class="delete">
  Delete
</button>

比较:

    <button @click="() => deleteTask(task.userId)" class="delete">
      Delete
    </button>

© www.soinside.com 2019 - 2024. All rights reserved.