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);
},
}
Since computed properties in VueJS are cached, there is no need for calculating unless there is a change in the items array. Vue 3 computed properties are reactive. Basically, the dependencies are reactive. So the execution of the below function will lead to a recalculation of the computed properties.
Vue 3 computed properties are reactive. Basically, the dependencies are reactive. So the execution of the below function will lead to a recalculation of the computed properties. You can read more Vue 3 Reactivity in Composition API. Basically, we are pushing a new item to the array.
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.
Think of a computed property as declaratively describing how to derive a value based on other values - its only responsibility should be computing and returning that value. Later in the guide we will discuss how we can perform side effects in reaction to state changes with watchers. The returned value from a computed property is derived state.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With