【问题标题】:Why updating object in array is not working in VUE?为什么更新数组中的对象在 VUE 中不起作用?
【发布时间】:2021-12-31 02:41:45
【问题描述】:

我正在尝试进行更新,并且我设法在 firebase 中进行了更新,但在商店中没有更新。这是我的代码

editCar() {
      let result = this.balmUI.validate(this.formData);
      let { valid, message } = result;
      this.message = message;
      console.log(`Vrei sa editezi masina: ${this.formData.vehicle}`);
      console.log(utils.url);

      if (valid) {
        let data = {
          vehicle: this.formData.vehicle,
          color: this.formData.color,
          fuel: this.formData.fuel,
          status: this.formData.status,
          price: this.formData.price,
        };

        let requestParameters = { ...utils.globalRequestParameters };
        let token = window.localStorage.getItem("token");
        requestParameters.headers.Authorization = "Bearer " + token;
        requestParameters.method = "PUT";
        requestParameters.body = JSON.stringify(data);

        fetch(utils.url + "cars/" + this.formData.id, requestParameters)
          .then((res) => res.json())
          .then((res) => {
            console.log(res.message);
            if (
              res.message === "Decoding error!" ||
              res.message === "Your token expired!"
            ) {
              console.log("nu ai voie!");
            } else {
              data.id = res.id;
              this.$store.dispatch("editCar", data);
              this.$router.push("/");
            }
          });
      }

这是来自 store 的索引,其中包含我的突变和操作。其他一切正常

import { createStore } from 'vuex'

export default createStore({
  state: {
    cars: [],
    isAuthentif: false
  },
  getters: {
    cars: state => {
      return state.cars
    }
  },
  mutations: {
    SET_AUTH: (state, status) => {
      state.isAuthentif = status
    },
    SET_CARS: (state, cars) => {
      state.cars = cars
    },
    ADD_CAR: (state, car) => {
      state.cars.push(car)
    },
    DELETE_CAR: (state, id) => {
      var index = state.cars.findIndex(car => car.id == id)
      state.cars.splice(index, 1);
    },
    EDIT_CAR: (state, car) => {
      state.cars.forEach(c => {
        if(c.id === car.id) {
          c = car;
        }
      })
    }
  },
  actions: {
    login: ({ commit }, payload) => {
      commit('SET_AUTH', payload)
    },
    fetchCars: ({ commit }, payload) => {
      commit('SET_CARS', payload)
    },
    addCar: ({ commit }, payload) => {
      commit('ADD_CAR', payload)
    },
    deleteCar: ({ commit }, payload) => {
      commit('DELETE_CAR', payload)
    },
    editCar: ({ commit }, payload) => {
      commit('EDIT_CAR', payload)
    }
  },
  modules: {
  }
})

EDIT_CAR 是问题所在,我认为。 怎么了?为什么它没有在屏幕上更新。 我也试过用这个https://vuex.vuejs.org/guide/mutations.html#object-style-commit 像这样c = {...c, car} 但不工作

【问题讨论】:

  • 什么是state.cars?是基元数组还是对象数组?
  • 对象数组@Terry
  • 是否可以改为分享minimal reproducible example
  • 我的数组列表中的对象在数据库中更新,但不是应用程序页面。在手动刷新后更新应用页面@Terry

标签: vuex vuejs3 mutation


【解决方案1】:

您的问题不在于突变。问题出在您的 editCar() 中 this.$store.dispatch("editCar", data); 您输入数据,并使用车辆、颜色、燃料、状态和价格,然后在您的突变中验证 ID。你没有传递任何id。如果您不想要自己的身份,可以创建一个新对象,如下所示:

editCar() {
      let result = this.balmUI.validate(this.formData);
      let { valid, message } = result;
      this.message = message;
      console.log(`Vrei sa editezi masina: ${this.formData.vehicle}`);
      console.log(utils.url);

      if (valid) {
        let data = {
          vehicle: this.formData.vehicle,
          color: this.formData.color,
          fuel: this.formData.fuel,
          status: this.formData.status,
          price: this.formData.price,
        };

        let requestParameters = { ...utils.globalRequestParameters };
        let token = window.localStorage.getItem("token");
        requestParameters.headers.Authorization = "Bearer " + token;
        requestParameters.method = "PUT";
        requestParameters.body = JSON.stringify(data);

        fetch(utils.url + "cars/" + this.formData.id, requestParameters)
          .then((res) => res.json())
          .then((res) => {
            console.log(res.message);
            if (
              res.message === "Decoding error!" ||
              res.message === "Your token expired!"
            ) {
              console.log("nu ai voie!");
            } else {
              let newData = {
                id: this.formData.id,
                vehicle: data.vehicle,
                color: data.color,
                fuel: data.fuel,
                status: data.status,
                price: data.price,
              };
              this.$store.dispatch("editCar", newData);
              this.$router.push("/");
            }
          });
      }
    },

在你的变异中也可以做这样的事情:

EDIT_CAR: (state, car) => {
      Object.assign(state.cars[state.cars.findIndex(c => c.id === car.id)], car);
    }

【讨论】:

    【解决方案2】:

    您能否尝试将您的 EDIT_CAR 突变更改为:

    const index = state.cars.findIndex(x => x.id === car.id)
    state.cars.splice(index, 1, car)
    

    如果您还没有这样做,请将 console.log(car) 放在突变的开头,以确保它被调用并且汽车有效负载是您所期望的。

    【讨论】:

    • 在控制台日志中是我期望的有效载荷汽车,但在我的列表中值没有改变:/
    • 也许问题不在于突变。也许这就是我进行此更新的方式。我有一个汽车列表,当我单击一辆车的编辑按钮时,我重定向到另一个路由器,在那里我有一个表格,我用我的汽车传输参数,然后我回到我没有改变的列表
    • 更新,问题出在突变上。我的 state.cars 没有改变,我不明白为什么。另外,您的回答不好,因为它在我的列表中添加了另一辆车而不是替换它
    • 好吧,不替换它不添加的对象。而且它比使用 Object.assign 更好。如果 id 未在有效负载中设置,则表示 data.id = res.id 是问题所在。
    猜你喜欢
    • 2022-12-01
    • 2017-08-03
    • 1970-01-01
    • 2018-06-20
    • 2020-11-13
    • 1970-01-01
    • 2020-09-17
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多