[Vuejs]-How to fire an event on Vue switch change

4πŸ‘

βœ…

I would recommend using a 2-way computed property for your model (Vue 2).
Attempted to update code here, but obvs not tested without your Vuex setup.
For reference, please see Two-Way Computed Property

data: function(){
  return {
    noAvailableMonitoring: false
  }
},
computed: {
  report() { return this.$store.getters.currentReport },
  isBeingMonitored() { return this.$store.getters.isBeingMonitored },
  availableMonitoring() { return this.$store.getters.checkAvailableMonitoring },
  toggle: {
    get() {
      return this.$store.getters.getToggle;
    },
    set() {
      if(this.availableMonitoring) {
        let dto = {
          reportToken: this.report.reportToken,
          version: this.report.version
        }
        this.$store.dispatch('TOGGLE_MONITORING', dto).then(response => {
        }, error => {
          console.log("Failed.")
        });
      } else {
        this.$store.commit('setToggle', false);
        this.noAvailableMonitoring = true;
      }
    }
  }
}

2πŸ‘

Instead of having a watch, create a new computed named clickToggle. Its get function returns toggle, its set function does what you’re doing in your watch (as well as, ultimately, setting toggle). Your mounted can adjust toggle with impunity. Only changes to clickToggle will do the other stuff.

πŸ‘€Roy J

Leave a comment