删除商店中的项目 Vuex

时间:2021-03-24 11:50:53

标签: vue.js nuxt.js vuex

我想删除我商店中的一个项目。 我看到了这个解决方案 https://stackoverflow.com/a/59686164/11984242,这似乎是我正在寻找的,但我的对象中有另一个“级别”,所以我不知道如何从子级别中删除元素。

我的数据结构。

{
    id: 1,
    name: 'My customer one',
    projects: [
        {
            id: 1,
            name: 'name',
            tests: [
                {
                    id: 1,
                    name: 'name test'
                },
                {
                    id: 2,
                    name: 'name test 2'
                }
            ]
        },
        {
            id: 2,
            name: 'other name'
        }
    ]
}

所以我看到了如何使用上面的链接删除项目。但是如何删除一行测试?

我在我的 vue 中这样做:

this.$store.commit("deleteTest", this.idProject, e)

这个在我的店里:

deleteTest(state, {data, e}) {
    const allTestsOfProject = state.listProjects.projects.find(p => p.id === data)
    console.log("all", allTestsOfProject)
    const oneTest = allTestsOfProject.studies.find(q => q.id === e)
    console.log("one test", oneTest)
    //state.listProjects.projects.splice(oneTest, 1)
  }

非常感谢您的帮助

1 个答案:

答案 0 :(得分:5)

您的代码有两个问题:

第一个问题

commit 函数只需要 2 个参数:

  1. 提交名称(作为字符串)
  2. 有效载荷对象

所以如果你想传递多个道具,你应该将它们作为一个对象传递

this.$store.commit("deleteTest", this.idProject, e) // WON'T WORK
this.$store.commit("deleteTest", {data: this.idProject, e}) // WILL WORK

现在您可以拨打 deleteTest(state, {data, e})

第二个问题

你应该得到测试对象的INDEX,而不是OBJECT本身

const oneTest = allTestsOfProject.studies.find(q => q.id === e) // WON'T WORK
const oneTest = allTestsOfProject.studies.findIndex(q => q.id === e) // WILL WORK

现在您可以调用:allTestsOfProject.studies.findIndex (q => q.id === e) 删除您的测试

相关问题