Nuxt.js fetch 方法

fetch 方法

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

  • 类型: Function

如果页面组件设置了 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>

store/index.js

// ...
export const actions = {
  async GET_STARS ({ commit }) {
    const { data } = await axios.get(http://my-api/stars)
    commit(SET_STARS, data)
  }
}

监听 query 字符串的改变

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

作者:terry,如若转载,请注明出处:https://www.web176.com/nuxt/22393.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年5月24日
下一篇 2023年5月24日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注