0%

在Nuxt中使用Axios-基礎使用

在Nuxt中額外提供了一個asyncData的屬性,讓服務器在渲染組件之前先異步獲取數據,也有以往會在Vue使用到的methods/created/mounted…等屬性,而非同步獲取數據又有Promise與ES7的 async/await兩種方法,這邊就來記錄一下在不同情境下的使用方法

前置作業

先安裝nuxt提供的axios

1
npm install @nuxtjs/axios

接著在nuxt.config.js中設定

1
2
3
4
5
6
7
8
9
module.exports = {
modules: [
'@nuxtjs/axios',
],

axios: {
// proxyHeaders: false
}
}

AsyncData

asyncData方法只會在 page component每次被加載前調用
在server-side 只有在請求網頁的時候被調用
在client-side時只有在路由更新時會被調用
而這個方法會接收一個context的物件當成第一個參數
也因為他是在component被加載前調用,所以要注意在asyncData裡面不能使用this

在asyncData中return的數據會直接取代data中的數據,然後再渲染到畫面上

Promise

下面是利用在asyncData屬性中利用Promise來非同步獲取數據的範例,可以看到asyncData裡面帶了一個$axios,而為什麼要帶一個$axios,是因為asyncData會帶一個context的參數,context參數裡面有一個包含所有pulgins的Vue根實例,如果想獲取$axios就可以在方法裡面用context.app.$axios來獲取,這邊直接利用{$axios}來解構賦值

1
2
3
4
5
6
7
8
asyncData({ $axios }) {
const api = `https://dog.ceo/api/breeds/image/random`;
return $axios.get(api).then(respons =>{
console.log(respons);
let image = respons.data.message;
return{image};
})
}

Async/Await

基本上只是把Promise的用法改成使用Async/Await,但有些不同的是,在$axios後面的方法本來是get,要改成$get

1
2
3
4
5
6
7
8
9
async asyncData({ $axios }) {
try{
const respons = await $axios.$get('https://dog.ceo/api/breeds/image/random');
let image = respons.message;
return{image};
}catch(err){
console.log(err);
}
}

methods/created/mounted…

跟前面的asyncData不同,methods、created等屬性,它們沒有context的物件當成默認參數,是在元件加載之後才會呼叫,所以可以使用this。
因為跟asyncData不同,所以呼叫使用axios的方法也不同,下面範例會以在methods中的情境來示範

Promise

這邊可以看到直接在方法裡面透過this就可以呼叫$axios

1
2
3
4
5
6
7
8
methods: {
getDogImage() {
const api = `https://dog.ceo/api/breeds/image/random`;
this.$axios.get(api).then(respons => {
this.image = respons.data.message
});
}
}

Async/Await

這邊就大同小異,一樣是可以透過this來呼叫$axios

1
2
3
4
5
6
7
8
9
10
11
methods: {
async getDogImage() {
try{
const api = `https://dog.ceo/api/breeds/image/random`;
const respons = await vm.$axios.$get(api);
this.image = respons.message
}catch(err){
console.log(err);
}
}
}

Dog API
Nuxt-Context
安全,輕鬆的Axios與Nuxt.js集成
vue 中使用 async/await 將 axios 異步請求同步化處理
簡單理解 JavaScript Async 和 Await
nuxt-axios
Nuxt.js 中 asyncData 使用方法介紹
NuxtJS 通過 2種方式引入axios進行異步數據請求