[Vuejs]-Can't get data of computed state from store – Vue

2👍

Like I wrote in the comments, the OPs problem is that he’s accessing a store property that is not available (probably waiting on an AJAX request to come in) when the component is mounted.

Instead of eagerly assuming the data is present when the component is mounted, I suggested that the store property be watched and this.init() called when the propery is loaded.

However, I think this may not be the right approach, since the watch method will be called every time the property changes, which is not semantic for the case of doing prep work on data. I can suggest two solutions that I think are more elegant.

1. Trigger an event when the data is loaded

It’s easy to set up a global messaging bus in Vue (see, for example, this post).

Assuming that the property is being loaded in a Vuex action,the flow would be similar to:

{
  ...
  actions: {
    async comments() {
      try {
        await loadComments()

        EventBus.trigger("comments:load:success")
      } catch (e) {
        EventBus.trigger("comments:load:error", e)
      }
    }
  }
  ...
}

You can gripe a bit about reactivity and events going agains the reactive philosophy. But this may be an example of a case where events are just more semantic.

2. The reactive approach

I try to keep computation outside of my views. Instead of defining chunkify inside your component, you can instead tie that in to your store.

So, say that I have a JavaScrip module called store that exports the Vuex store. I would define chunkify as a named function in that module

function chunkify (a, n) {
   ...
}

(This can be defined at the bottom of the JS module, for readability, thanks to function hoisting.)

Then, in your store definition,

const store = new Vuex.Store({
  state: { ... },
  ...
  getters: {
    chunkedComments (state) {
      return function (chunks) {
        if (state.comments)
          return chunkify(state.comments, chunks);

        return state.comments
      }
    }
  }
  ...
})

In your component, the computed prop would now be

computed: {
  comments() {
    return this.$store.getters.chunkedComments(3);
  },
}

Then the update cascase will flow from the getter, which will update when comments are retrieved, which will update the component’s computed prop, which will update the ui.

0👍

Use getters, merge chuckify and init function inside the getter.And for computed comment function will return this.$store.getters.YOURFUNC (merge of chuckify and init function). do not add anything inside mounted.

Leave a comment