第一部分
asyncData
和fetch
具有不同的本质特点,因此在使用asyncData
时有一个重要的优势 - Nuxt在导航到下一页之前等待 asyncData 钩子完成。
引用https://nuxtjs.org/docs/2.x/features/data-fetching#async-data:
与fetch不同,并行调用每个页面组件的asyncData方法。 在路由转换期间解析返回的 promise,这表示客户端路由转换期间无需“加载占位符”(虽然可以使用加载条将加载状态指示给用户)。 Nuxt将等待执行完所有的asyncData钩子后再导航到下一页,如果发生错误则显示错误页。
实际上意味着什么?
假设您有以下布局结构:
使用fetch
时,当您打开新页面时,您可能会看到几秒钟只显示 Header 和 Footer(因为正在下载 Content 的数据)。 使用asyncData
避免了这个问题,您将能够看到包含Header+Content+Footer的新页面(但该方法的缺点是需要等待几秒钟下载 Content 数据)。
第二部分
我看到网上有很多不同的地方说,如果要将东西存储在vuex中,就需要使用fetch
- 这是不正确的。
下面的代码(来自我的项目)中包含了实现asyncData
和fetch
双重功能的代码,均可将数据存储到vuex中。
<script>
import { mapActions, mapMutations, mapState } from 'vuex'
export default {
name: 'PagesBlog',
async asyncData ({ store }) {
if (!store.state.global.blogAuthors.length) {
store.commit('global/blogAuthorsSet', await blogAuthorsDownload())
}
await store.dispatch('global/blogsDownloadAndSet')
},
async fetch () {
if (!this.blogAuthors.length) {
this.blogAuthorsSet(await blogAuthorsDownload())
}
await this.blogsDownloadAndSet()
},
computed: {
...mapState('global', [
'blogAuthors'
])
},
methods: {
...mapActions('global', [
'blogsDownloadAndSet'
]),
...mapMutations('global', [
'blogAuthorsSet'
])
}
</script>
概要
如果您有一些重要的数据(无论是对用户可见还是不可见,但需要进行某些隐藏计算)- 请使用asyncData
。
如果您想查看包含所有信息的页面(例如具有标题+内容+页脚)- 请使用asyncData
。
如果您有一些稍后可以加载的数据- 请使用fetch
。
Fetch钩子和Nuxt生命周期
created & mounted
钩子函数总是在客户端运行。对于特定路由的第一次请求,asyncData & fetch
将在服务器端运行。因此,使用asyncData & fetch
,您有机会在客户端加载数据,而无需在客户端进行页面加载后的任何 ajax 请求,就像您为created & mounted
钩子函数所做的那样。 - divineasyncData
还是fetch
中的任何内容都会首先被调用,然后才会调用created
钩子函数,最后才会调用mounted
钩子函数。因此,在组件被创建之前,asyncData
或fetch
就已经被调用了。 - divine