使用 nuxtjs 在我的页面中使用异步数据
using async data in my page using nuxtjs
我读过在 nuxtjs 页面中使用异步数据或获取是一种更好的方法,而不是使用创建的钩子。
虽然我正在努力让我的代码正常工作
我有以下内容(效果很好)
created () {
this.$store.dispatch('cases/getCase', this.$route.params.caseId );
},
但是请问我该如何更改它以使用异步方法,并在需要时能够 return 多个状态。
我尝试了以下方法
async asyncData ({ params }) {
const thisCase = await this.$store.dispatch('cases/getCase', this.$route.params.caseId );
// constant thisUser
return { thisCase }
// return { thisCase, thisUser}
},
但这会产生错误
undefined is not an object (evaluating 'this.$store')
谁能告诉我我做错了什么
谢谢
this
在 asyncData/fetch 中不可用。它甚至在 docs 的特殊橙色警告中说明。
You do NOT have access of the component instance through this inside
asyncData because it is called before initiating the component.
再次如文档中所述
method receives the context object as the first argument, you can use
it to fetch some data and return the component data.
上下文是您应该从哪里获取您的商店。 Here docs 上下文。
所以你的代码是
async asyncData ({ params, store }) {
const thisCase = await store.dispatch('cases/getCase', params.caseId )
return { thisCase }
},
我读过在 nuxtjs 页面中使用异步数据或获取是一种更好的方法,而不是使用创建的钩子。
虽然我正在努力让我的代码正常工作
我有以下内容(效果很好)
created () {
this.$store.dispatch('cases/getCase', this.$route.params.caseId );
},
但是请问我该如何更改它以使用异步方法,并在需要时能够 return 多个状态。
我尝试了以下方法
async asyncData ({ params }) {
const thisCase = await this.$store.dispatch('cases/getCase', this.$route.params.caseId );
// constant thisUser
return { thisCase }
// return { thisCase, thisUser}
},
但这会产生错误
undefined is not an object (evaluating 'this.$store')
谁能告诉我我做错了什么
谢谢
this
在 asyncData/fetch 中不可用。它甚至在 docs 的特殊橙色警告中说明。
You do NOT have access of the component instance through this inside asyncData because it is called before initiating the component.
再次如文档中所述
method receives the context object as the first argument, you can use it to fetch some data and return the component data.
上下文是您应该从哪里获取您的商店。 Here docs 上下文。
所以你的代码是
async asyncData ({ params, store }) {
const thisCase = await store.dispatch('cases/getCase', params.caseId )
return { thisCase }
},