8
votes

Is it possible to get computed property value in created hook? My current implementation doesn’t work. My understanding is created hook would be called first which would call my async method and async method needs the computed property, but by the time computed property becomes available the created hook has already been executed with the “undefined” parameter.

Please suggest how can i make computed property available to created hook method.

created() {
        this.fetchPropertyOptions();
},
computed: {
    propertyList() {
        return this.data.value;
    },
},
methods: {
    async fetchPropertyOptions() {
        this.propertyOptionsMap = await api.GetOptions(this.propertyList);
    },
}
1
this.data.value should be this.value - Joseph Silber
Try using mounted() rather than created()? - Ru Chern Chong
@zubairm - it works for me: codepen.io/JosephSilber/pen/erZqYW - Joseph Silber
Thanks all for your help, Setting up a watcher on the property worked for me - zm10
Could anyone please suggest why my question is down-voted :( - zm10

1 Answers

14
votes

The Vue component creation goes through different lifecycles. There's an excellent diagram in the lifecycle diagram section of the documentation.

Reading the above mentioned diagram from top to bottom, you notice the created hook that you use in your example. It is called directly after Init injections & reactivity. This is where e.g. the props, data & computed are initialised. Right after that, the created lifecycle method is called.

As a practical example, the codepen Joseph Silber linked in his answer shows the successful usage of a computed property in the created method.

In fact, the only lifecycle method that can't use the injections & reactivity is beforeCreated. All other lifecycle methods, e.g. mounted, updated and even beforeDestroy & destroyed have access to it.