programing

vuex 스토어에서 깊이 있는(내포된) 변화를 감시하려면 어떻게 해야 합니까?

yoursource 2022. 8. 27. 14:10
반응형

vuex 스토어에서 깊이 있는(내포된) 변화를 감시하려면 어떻게 해야 합니까?

  created() {
    this.$store.watch(
      state => {
        return state.httpRequest;
      },
      (oldVal, newVal) => {
        console.log(oldVal, newVal);
      }
    );
  },

로 트리거되지 않습니다.httpRequest는 객체입니다.

합격할 수 있다{ deep: true }세 번째 파라미터로 지정합니다.

created() {
  this.$store.watch(
    state => {
      return state.httpRequest;
    },
    (oldVal, newVal) => {
      console.log(oldVal, newVal);
    },
    { deep: true }
  );
}

다음 매뉴얼은watch방법.

다음은 간단한 예입니다.

Vue.config.productionTip = false;
Vue.config.devtools = false;

const store = new Vuex.Store({
  state: { httpRequest: null },
  mutations: {
  	changeRequest(state) {
    	if (!state.httpRequest) {
        state.httpRequest = { foo: 1 };
      } else {
        state.httpRequest.foo++;
      }
    }
  }
});

new Vue({
	el: '#app',
  store,
  methods: {
    onClick() {
      this.$store.commit('changeRequest')
    }
  },
  created() {
    this.$store.watch(
      state => {
        return state.httpRequest;
      },
      (oldVal, newVal) => {
        console.log(oldVal, newVal);
      },
      { deep: true }
    );
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="onClick">
    Click
  </button>
</div>

에서 상태를 매핑할 수 있습니다.vuexcomputed을 경유하여 분할하다mapState필요한 가치를 얻다

computed : {
   ...mapState('yourNameSpace', {
      httpRequest : state => state.httpRequest
   })
}

언급URL : https://stackoverflow.com/questions/57558558/how-can-i-watch-for-deep-nested-changes-in-a-vuex-store

반응형