[Vuejs]-Vuejs need to watch bool multiple time

-1👍

There is no event that happens when you assign a reactive item the same value it already had. You need to do something to catch those assignments.

You can use a settable computed for this. It will be called any time you try to assign a value to the variable. You will just need to ensure that you set your computed, and not the store variable that it is based on.

new Vue({
  el: '#app',
  data: {
    storeStateMock: true,
    trueCount: 0,
    changeCount: 0
  },
  computed: {
    recommendationSetCorrectly: {
      get() { return this.storeStateMock; },
      set(v) {
        if (v) { ++this.trueCount; }
        this.storeStateMock = v;
      }
    }
  },
  watch: {
    recommendationSetCorrectly() {
      ++this.changeCount;
    }
  },
  created() {
    setInterval(() => {
      this.recommendationSetCorrectly = Math.random() > 0.5;
    }, 1200);
  }
});
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  {{ recommendationSetCorrectly }} {{ trueCount }} {{ changeCount }}
</div>

You could also add a trueCount item to your $store, and increment it in the mutation that sets your boolean. Then you could watch trueCount.

Leave a comment