Search code examples
vue.jsvuex

How to call a method after Vuex data is available?


I would like to call a method once, as soon as possible after its component loads, but it needs to be after a computed property that gets data from Vuex is defined.

For example:

  computed: {
    my_data: function() {
      return this.$store.state.my_data;
    }
  },
  methods: {
    useData: function(){
      axios.post('api/fetch', {'data': this.my_data});
    }
  },
  mounted() {
    this.useData(); //error: this.my_data is undefined;
  },
  watch: {
    my_data: function(){
      this.useData(); //never triggers
    }
  }

If I call this.useData() from mounted, my_data is still undefined. I tried setting a watcher on my_data, but it never triggers. I feel like I'm missing something obvious here.


Solution

  • It turns out the "undefined" error was caused by another object that shared a key name with my stored object. Unfortunately, the nebulous error message sent me on a wild goose chase after I assumed the stored object was the issue based on my inexperience with Vuex.