API fetch方法
fetch 用于在渲染前填充应用的状态树(store)数据, 与 asyncData 类似,不同的是它不会设置组件的数据。
如果组件设置了 fetch ,它会在组件每次加载前被(在服务端或切换至目标路由之前)。
fetch 的第参数是组件的上下文对象 context,我们可以用 fetch 来数据填充应用的状态树。为了让过程可以异步,你需要返回 Promise,Nuxt.js 会等这个 promise 完成后再渲染组件。
警告: 您无法在内部使用this组件实例,fetch是在组件初始化之前被
例如 pages/index.vue:
<template> <h1>Stars: {{ $store.state.stars }}</h1> </template> <script> export default { fetch ({ store, params }) { return axios.get('http://my-api/stars') .then((res) => { store.commit('setStars', res.data) }) } } </script>
你也可以使用 async 或 await 的模式简化如下:
<template> <h1>Stars: {{ $store.state.stars }}</h1> </template> <script> export default { async fetch ({ store, params }) { let { data } = await axios.get('http://my-api/stars') store.commit('setStars', data) } } </script>
Vuex
如果要在fetch中并操作store,请使用store.dispatch,但是要确保在内部使用async / await等待操作结束:
<script> export default { async fetch ({ store, params }) { await store.dispatch('GET_STARS'); } } </script>
// ... export const actions = { async GET_STARS ({ commit }) { const { data } = await axios.get('http://my-api/stars') commit('SET_STARS', data) } }
监听 query 字符串的改变
认情况下,不会在字符串更改时fetch。如果想更改此行为,例如,在编写组件时,您可以设置通过组件的watchQuery来监听参数的变化。了解更多有关 API watchQuery page的信息。