Avoid using `this` in `asyncData` and `fetch` hooksJS-W1011
this
is called inside asyncData
before the component is initialized, the component instance doesn't exist and can not be accessed using it. It is therefore not to use this
inside asyncData
hooks.
asyncData
is a hook for universal data fetching and it is only available for pages. Unlike fetch
, which requires you to set properties on the component instance (or dispatch Vuex actions) to save your async state, asyncData
merges its return value into your component's local state.
Also, asyncData
can only be used for page-level components, and since [email protected]
unlike fetch
, asyncData
cannot access the component instance (this
).
The recommended way to fix this issue is to use context
, which comes as an argument of asyncData
. It can be used to fetch some data, and Nuxt.js will automatically merge the returned object with the component data.
Bad Practice
export default {
async asyncData() {
if (this.$route.path === 'name') {
}
}
}
Recommended
export default {
async asyncData(context) {
if (context.route.path === 'name') {
}
}
}