fetch 方法

fetch 方法用于在渲染页面前填充应用的状态树(store)数据, 与 asyncData 方法类似,不同的是它不会设置组件的数据。

  • 类型: Function如果页面组件设置了 fetch 方法,它会在组件每次加载前被调用(在服务端或切换至目标路由之前)。

fetch 方法的第一个参数是页面组件的上下文对象 context,我们可以用 fetch 方法来获取数据填充应用的状态树。为了让获取过程可以异步,你需要返回一个 Promise,Nuxt.js 会等这个 promise 完成后再渲染组件。

警告: 您无法在内部使用this获取组件实例fetch是在组件初始化之前被调用

例如 pages/index.vue

  1. <template>
  2. <h1>Stars: {{ $store.state.stars }}</h1>
  3. </template>
  4. <script>
  5. export default {
  6. fetch ({ store, params }) {
  7. return axios.get('http://my-api/stars')
  8. .then((res) => {
  9. store.commit('setStars', res.data)
  10. })
  11. }
  12. }
  13. </script>

你也可以使用 asyncawait 的模式简化代码如下:

  1. <template>
  2. <h1>Stars: {{ $store.state.stars }}</h1>
  3. </template>
  4. <script>
  5. export default {
  6. async fetch ({ store, params }) {
  7. let { data } = await axios.get('http://my-api/stars')
  8. store.commit('setStars', data)
  9. }
  10. }
  11. </script>

Vuex

如果要在fetch中调用并操作store,请使用store.dispatch,但是要确保在内部使用async / await等待操作结束:

  1. <script>
  2. export default {
  3. async fetch ({ store, params }) {
  4. await store.dispatch('GET_STARS');
  5. }
  6. }
  7. </script>

store/index.js

  1. // ...
  2. export const actions = {
  3. async GET_STARS ({ commit }) {
  4. const { data } = await axios.get('http://my-api/stars')
  5. commit('SET_STARS', data)
  6. }
  7. }

监听 query 字符串的改变

默认情况下,不会在查询字符串更改时调用fetch方法。如果想更改此行为,例如,在编写分页组件时,您可以设置通过页面组件的watchQuery属性来监听参数的变化。了解更多有关 API watchQuery page的信息。