0

I'm using VueJs and I need to watch a bool multiple time and when its true, do an action. I have found that the watch doesn't trigger when the current value is change for the same value (https://github.com/vuejs/vue/issues/1302).

For the moment, I just set the bool to false before every action where I can change the value and inside my watch I have a if where I check if the bool is true. Someone know a better way to do that?

watch: {
  '$store.state.recommandationModule.recommandationSetCorrectly': function (val) {
    if (val) {
      // Do action
    }
  }
}
nayan perron
  • 85
  • 1
  • 7
  • 2
    It sounds like you have an event that happens that sets the boolean and your action here should listen for that event, too. – Roy J Mar 26 '18 at 12:59
  • @RoyJ I have multiple event where i change the bool to true or false. The watch does't trigger if the bool change for what he was before, but I need to make the action even if the bool was true and I change it to true again. – nayan perron Mar 26 '18 at 18:03
  • https://stackoverflow.com/questions/42822948/how-should-i-handle-events-in-vuex – Roy J Mar 27 '18 at 12:40

1 Answers1

-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.

tony19
  • 125,647
  • 18
  • 229
  • 307
Roy J
  • 42,522
  • 10
  • 78
  • 102
  • make a count could work, but I don't know if it's the best idea and if that's clean. Also, the bool need to be in the store, because it can be use inside multiple Vue. – nayan perron Mar 27 '18 at 12:11