[Vuejs]-Trigger method directly from computed (Vue.js)

3👍

You really shouldn’t have sideEffects in your computed Functions.
see here: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free

Anyways to answer your question, you can do the following:

//computed
computed: {
  test() {
    if (this.$store.state.boolean) {
      this.trigger_method();
    }

    // as this is a getter function you will need to return something.
    return this.$store.state.boolean
  },
}

my recommended approach for your problem would be:

watch: {
  '$store.state.boolean': function() {
    if ($store.state.boolean === true) {
      this.trigger_method();
    }
  }
}

with this you dont need the computed. if you need the computed value somewhere in your code template or any method, you should keep it and use the computed & watch method you are already using but trying to avoid.

Third option, if the Function is not Component specific you could define a subscriber for your Vuex Store, see here: https://vuex.vuejs.org/api/#subscribe

Leave a comment