1

I have a component whose data is initialized by ajax. I know vue.js has provide several lifecycle hooks: Lifecycle-Diagram. But for ajax to initialize the data, which hook(beforeCreate, create, mounted, etc) is the best place to do it:

hook_name: function() {
    ajaxCall(function(data) {
        me.data = data;
    });
}

Currently, i do it in mounted, making it to re-render the component. But i think we should get the data before the first render. Can someone figure out the best way to do it?

1 Answer 1

3

If you want to initialize your component with data you receive from a request, created() would be the most appropriate hook to use but it is a request, it might not resolve by the end of created or even mounted() (when even your DOM is ready to show content!).

So do have your component initialized with empty data like:

data () {
  return {
    listOfItems: [],
    someKindOfConfig: {},
    orSomeSpecialValue: null
  }
}

and assign the actual values when you receive them in your created hook as these empty data properties would be available at that point of time, like:

created () {
  someAPICall()
    .then(data => {
       this.listOfItems = data.listOfItems
    })
    /**
    *  Notice the use of arrow functions, without those [this] would
    *  not have the context of the component.
    */
}

It seems like you aren't using (or aren't planning to use) vuex but I'd highly recommend you to use it for for managing your data in stores. If you use vuex you can have actions which can make these api calls and by using simple getters in your component you would have access to the values returned by the request.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.