Nuxt.js fetch 方法

2020-02-13 17:59 更新

fetch 方法

fetch 方法用于在渲染頁面前填充應(yīng)用的狀態(tài)樹(store)數(shù)據(jù), 與 asyncData 方法類似,不同的是它不會設(shè)置組件的數(shù)據(jù)。
  • 類型: Function

如果頁面組件設(shè)置了 fetch 方法,它會在組件每次加載前被調(diào)用(在服務(wù)端或切換至目標(biāo)路由之前)。

fetch 方法的第一個參數(shù)是頁面組件的上下文對象 context,我們可以用 fetch 方法來獲取數(shù)據(jù)填充應(yīng)用的狀態(tài)樹。為了讓獲取過程可以異步,你需要返回一個 Promise,Nuxt.js 會等這個 promise 完成后再渲染組件。

警告: 您無法在內(nèi)部使用this獲取組件實(shí)例,fetch是在組件初始化之前被調(diào)用

例如 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中調(diào)用并操作store,請使用store.dispatch,但是要確保在內(nèi)部使用async / await等待操作結(jié)束:

<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)
  }
}

監(jiān)聽 query 字符串的改變

默認(rèn)情況下,不會在查詢字符串更改時調(diào)用fetch方法。如果想更改此行為,例如,在編寫分頁組件時,您可以設(shè)置通過頁面組件的watchQuery屬性來監(jiān)聽參數(shù)的變化。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號