一:安裝axios依賴
cnpm install axios --save
二:創建axios實例
創建api接口請求文件,方便管理接口
新建文件:src/api/index.js
三:文件內容,在文件中設置了一個獲取天氣預報的接口進行測試
import axios from 'axios'
// 創建axios實例
const instance = axios.create({
baseURL: '',
timeout: 60000
})
// 請求攔截器
instance.interceptors.request.use(
config => {
// 在此處攔截過濾請求的內容和增加請求頭設置
console.log('項目請求了一個接口,此時攔截,會取消該請求')
// 請求頭設置
// config.headers['xxx'] = 'xxxxxxx'
return config
},
error => {
// console.log(error)
Promise.reject(error)
}
)
// 響應攔截器
instance.interceptors.response.use(
response => {
// 處理返回的結果
console.log('後臺接口返回了內容,可以在此處判斷後臺接口返回的是正常數據還是錯誤信息')
// 正常返回數據
return response
},
error => {
if (error.response) {
switch (error.response.status) {
case 400:
alert(error.response.data.message || '請求參數異常')
break
case 403:
alert(error.response.data.message || '無訪問權限')
break
default:
alert(error.response.data.message || '服務端異常')
}
}
// 返回錯誤信息
return Promise.reject(error)
})
// 設置項目中需要用到的api,如果api接口比較多,也可以提取出來,然後在此文件導入
const api = {
// 測試獲取天氣預報信息
getWeatherInfo (params) {
return new Promise((resolve, reject) => {
instance.get(`https://www.tianqiapi.com/api/`, {
params: params
}).then((res) => {
resolve(res)
})
})
}
}
export default api
四:在組件中調用設置的接口
測試組件內容:
<template>
<div>
<!-- 獲取天氣預報信息按鈕 -->
<div>
<button type="button" @click="getWeather">獲取天氣預報信息</button>
</div>
<!-- 展示天氣預報信息 -->
<h2>天氣預報信息如下:</h2>
<div>{{weather}}</div>
</div>
</template>
<script>
// 導入定義配置的接口
import api from '@/api'
export default {
data () {
return {
weather: null // 天氣預報信息
}
},
methods: {
/**
* 獲取天氣預報信息
**/
getWeather () {
api.getWeatherInfo({
version: 'v1'
}).then((res) => {
this.weather = res.data
})
}
}
}
</script>
<style scoped>
</style>
五:結果顯示