Home > Enterprise >  trigger method directly from computed (Vue.js)
trigger method directly from computed (Vue.js)

Time:08-03

I'm working with Vue 3 and VueX.

I want to know if it's possible to check in computed if my returned value is true and than trigger my method directly without an watcher.

Info: this.$store.state.boolean is changing sometimes, so if it's true I want to trigger my method.

Below you can see an example how I'm doing it right now:

//computed
computed: {
  test() {
    return this.$store.state.boolean;
  },
}

//watch
watch: {
  test(boolean) {
    if (boolean == true) {
      this.trigger_method();
    }
  }
},

//methods
method: {
  trigger_method() {
    console.log("TEST");
  }
}

CodePudding user response:

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

  • Related