programing

어레이의 개체 업데이트가 VUE에서 작동하지 않는 이유는 무엇입니까?

goodcopy 2022. 7. 31. 22:00
반응형

어레이의 개체 업데이트가 VUE에서 작동하지 않는 이유는 무엇입니까?

업데이트를 하려고 하는데, 방화벽 기지에서 해냈는데, 스토어에서 업데이트가 안 돼요.여기 제 코드가 있습니다.

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("/");
            }
          });
      }

이것은 나의 돌연변이와 액션을 나타내는 스토어의 인덱스입니다.그 외의 것은 정상적으로 동작하고 있다.

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}동작하지 않습니다.

네 문제는 돌연변이가 아니야문제는 여기 editCar()에 있습니다.this.$store.dispatch("editCar", data);데이터, 차량, 색상, 연료, 상태, 가격 등을 입력하고 돌연변이를 통해 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);
    }

EDIT_CAR 변환을 다음과 같이 변경할 수 있습니까?

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

아직 시작하지 않은 경우 변환 시작 부분에 console.log(car)를 배치하여 console.log(car)가 호출되고 차량 페이로드가 예상대로인지 확인합니다.

언급URL : https://stackoverflow.com/questions/70049823/why-updating-object-in-array-is-not-working-in-vue

반응형