首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从数组Vuex中删除项

无法从数组Vuex中删除项
EN

Stack Overflow用户
提问于 2020-12-20 20:31:23
回答 1查看 179关注 0票数 2

在尝试了我在这里找到的所有方法(包括this.$delete)之后,我无法从数组中删除项。

findIndexIndexOf返回-1,因此显然不起作用。filtersplice也不能工作。

我怀疑我做错了什么。我将非常感谢你的帮助

Vuex

代码语言:javascript
复制
  namespaced: true,
  state: {
    coefficients: [],
  },
  mutations: {
    getDataState(state, coefficients) {
      state.coefficients = coefficients;
    },
    itemDelete(state, item) {
      const index = state.coefficients.findIndex((el) => el.id === item.id);
      if (index > -1) state.coefficients.splice(index, 1);
      // #2 state.coefficients.splice(index, 1);
      // #3 
      /* const index = state.coefficients.indexOf(item);
      console.log(index, 'index');
      if (index > -1) {
        state.coefficients.splice(index, 1);
      } */
    },
  },
  actions: {
      getData({ commit }, userData) {
      api.get('/coefficients/')
        .then((res) => {
          commit('getDataState', {
            coefficients: res,
          });
        })
        .catch((error) => {
          console.log(error, 'error');
          commit('error');
        });
    },
      deleteData({ commit }, { id, item }) {
      api.delete(`/coefficients/${id}`)
        .then((res) => {
          commit('itemDelete', {
            item,
          });
          console.log(res, 'res');
        })
        .catch((error) => {
          console.log(error, 'error');
        });
    },
  },
}; 

组件

代码语言:javascript
复制
        <div v-for="(item, index) in this.rate.coefficients" :key="item.id">
          <div>{{ item.model }}</div>
          <div>{{ item.collection }}</div>
          <div>{{ item.title }}</div>
          <span v-on:click="deleteItem(item.id, item)">X</span>
         </div>
         
        /* ... */

         methods: {
          deleteItem(id, item) {
            this.$store.dispatch('rate/deleteData', { id, item });
            },
        },
         created() {
          this.$store.dispatch('rate/getData');
        },
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-20 20:35:23

itemDelete突变需要一个具有id属性的对象,但您传递给它的是一个具有item属性的对象,因为您在传递item时将其包装在一个普通对象中。

更改deleteData中的提交,以传递项目而不先包装它:

代码语言:javascript
复制
commit('itemDelete', item);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65379881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档