Nuxt fetch 使用
1、fetch方法
用于在渲染页面前填充应用的状态树(store)数据, 与 asyncData 方法类似,不同的是它不会设置组件的数据。
类型:Function
如果页面组件设置了 fetch
方法,它会在组件每次加载前被调用(在服务端或切换至目标路由之前)。
2、作用
监听 query 变更、导航切换等
3、区别
asyncData 和 fetch 的区别
- 组件限制
- asyncData 仅限于页面级组件。
- fetch 可用于任意组件。
- 获取上下文
- asyncData 不可以使用 this,只能通过回调参数获取上下文对象。
- fetch 可以使用 this。
- 数据操作
- asyncData 通过 return 合并 data 数据。
- fetch 可以使用 this 直接修改赋值。
- 调用时机
- asyncData 只在页面创建前调用。
- fetch 在页面实例创建后调用,并可以通过$fetch 方法随时触发,$fetchState.timestam 属性可以获取最后一次触发的时间戳。
- 错误处理
- asyncData 通过 error 参数抛出错误,但并不会在页面显示异常。
- fetch 可以使用 throw new Error()来抛出异常,在页面调用$fetchState.error 方法获取异常状态。
- 页面渲染
- asyncData 在页面创建前填充数据。
- fetch 可通过 fetchOnServer 属性设置是否允许在服务端获取数据,设置为 false 将可以在渲染数据时通过$fetchState.pendinding 获取加载状态。
4、示例
// 示例 1 单个请求 export default { async fetch() { this.bottom = await fetch('https://api.yfn.com/mall/module/homepage/v1/homepage/getBottomNavigation').then(res => res.json()) console.log(this.bottom, 'bottom') }, }
// 示例 2 单个请求 export default { async fetch() { this.bottom = await this.$api.mixins.getBottomNav(); console.log(this.bottom, 'bottom') }, }
// 示例 3 多个请求 export default { async fetch() { const [bottom1, bill] = await Promise.all([ this.$api.mixins.getBottomNav(), this.$api.mixins.getBillboard() ]) console.log(bottom1, bill, 'bottom') }, }
5、nuxt执行流程