'Nuxtjs: Access the data of the component from anonymous middleware
how can we access the data of the component (such as infos, similarPosts in this example) from the anonymous middleware in the nuxtjs application?
Solution 1:[1]
You cannot have access to data
in a middleware since it's run before the data
is binded to the page as seen in the lifecycle of Nuxt.
Meanwhile, you could access data
through vm
thanks to beforeRouteEnter or a similar router guard.
Solution 2:[2]
Try to do something like this:
asyncData(context) {
// Do stuff with the context
return {
title: "My Title created from context"
}
}
asyncData runs before loading the page component and will be called server side on the first request. This is what I was looking for, as I needed access to the context object while needing to set component variables before loading the component in the client.
Solution 3:[3]
As @kissu said, you can not do this, but as a workaround you can use Vuex. In this case it looks like:
middleware ({ store }) {
const x = store.state.STORE_MODULE_NAME.STATE_PARAMETER_NAME
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kissu |
Solution 2 | Bruno Silva |
Solution 3 | TitanFighter |