programing

Vuewatcher 및 Vuex가 제대로 작동하지 않음

javajsp 2023. 6. 8. 19:22

Vuewatcher 및 Vuex가 제대로 작동하지 않음

Vuex의 상태를 업데이트하는 구성 요소가 있으며 vue dev 도구를 통해 vuex 상태가 변경되었음을 알 수 있지만 vuex의 mapGeters 또는 mapState에 바인딩된 감시자를 통해 상태가 변경될 때 일부 논리를 실행하려고 하면 전혀 작동하지 않습니다.vuex의 코드:

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    companyDetails: {},
    //date: "",
    showSearchForm: false,   
    consumptionData: {
      dateTo: new Date(),
      dateFrom: new Date(new Date().setDate(new Date().getDate() - 7))
    }
  },
  getters: {
    getConsumptionData(state) {
      return state.consumptionData;
    }   
  },.....

Vuex에서 MapState 또는 MapGetters 주석 코드를 통해 데이터를 가져오는 watcher 및 계산된 속성의 코드는 내가 모든 옵션을 시도했다는 것을 의미합니다.

  computed: {
    // need to ask about reactiveness
    // ...mapGetters({
    //   consumptionDataVuex: "getConsumptionData"
    // })
    //  ...mapState({
    //  consumptionDataVuex: "ConsumptionData"
    //  })    
    consumptionDataVuex () {
      return this.$store.getters.getConsumptionData;
    }
  },
    watch: {
    consumptionDataVuex() {
      console.log("changed");
      this.getConsumption();
    }
  },.....

vuex에서 데이터를 동기적으로 가져오는 유일한 코드는 다음과 같습니다.

  created() {
    //console.log(this.parentData);
this.$store.watch(
  (state)=>{
    return this.$store.state.consumptionData // could also put a Getter here
  },
  (newValue, oldValue)=>{
    //something changed do something
    console.log(oldValue)
    console.log(newValue)
    this.getConsumption();
  },
//Optional Deep if you need it
    {
      deep:true
    }
  )
  },

그렇다면, 위의 코드는 상태에서 업데이트를 받을 수 없는 반면, 생성된 후크의 코드는 업데이트를 받을 수 없는 이유를 이해할 수 없습니다.인터넷의 많은 예들은 그것이 효과가 있어야 한다는 것을 증명합니다.

시계를 바꿔보세요.

    watch: {
        consumptionDataVuex: {
            handler () {
              console.log("changed");
              this.getConsumption();
            },
            deep: true
        }
    }

언급URL : https://stackoverflow.com/questions/53803863/vue-watcher-and-vuex-do-not-work-properly