Axios
??axios 是一個(gè)基于 Promise 的 HTTP 客戶端,不僅可以與 vue.js 一起使用,還可以與其他前端框架以及后端 Node.js 一起使用。當(dāng)你想從包括后端服務(wù)器在內(nèi)的外部服務(wù)獲取數(shù)據(jù)時(shí),可以使用axios 中的方法很方便的獲得數(shù)據(jù)內(nèi)容。在本文檔中,我們將介紹如何在 vue.js 版本 3 的環(huán)境中使用 axios。對(duì)于 Vue 3,它不僅解釋了如何將它與 Options API 一起使用,還解釋了如何將它與 Composition API 一起使用。
官方文件地址https://axios-http.com/docs/intro
第一章 Vue3項(xiàng)目創(chuàng)建 1 Vue CLI 創(chuàng)建vue項(xiàng)目
第一章 Vue3項(xiàng)目創(chuàng)建 2 使用 Webpack 5 搭建 vue項(xiàng)目
第一章 Vue3項(xiàng)目創(chuàng)建 3 Vite 創(chuàng)建 vue項(xiàng)目
第二章 Vue3 基礎(chǔ)語(yǔ)法指令
第三章 Vue Router路由器的使用
第四章 VUE常用 UI 庫(kù) 1 ( element-plus,Ant ,naiveui,ArcoDesign)
第四章 VUE常用 UI 庫(kù) 2 ( ailwind 后臺(tái)框架)
第五章 Vue 組件應(yīng)用 1( Props )
第五章 Vue 組件應(yīng)用 2 ( Emit )
第五章 Vue 組件應(yīng)用 3( Slots )
第五章 Vue 組件應(yīng)用 4 ( provide 和 inject )
第五章 Vue 組件應(yīng)用 5 (Vue 插件)
第六章 Pinia,Vuex與axios,VueUse 1(Pinia)
第六章 Pinia,Vuex與axios,VueUse 2(Vuex)
第六章 Pinia,Vuex與axios,VueUse 3(VueUse)
第六章 Pinia,Vuex與axios,VueUse 4(axios)
第七章 TypeScript 上
第七章 TypeScript 中
第七章 TypeScript 下 創(chuàng)建Trello 任務(wù)管理器
第八章 ESLint 與 測(cè)試 ( ESLint )
第八章 ESLint 與 測(cè)試 ( Jest )
第八章 ESLint 與 測(cè)試 (TypeScript 中Jest與檢測(cè)環(huán)境集成)
1 axios 設(shè)置
??我們的目標(biāo)是學(xué)習(xí)如何將 axios 與 vue.js 一起使用,使用 cdn模式是最快和最簡(jiǎn)單的方法。在原生的HTML中使用axios 的方法獲得數(shù)據(jù)。在瀏覽器訪問(wèn)它并顯示一個(gè)遠(yuǎn)程訪問(wèn)獲得數(shù)據(jù)列表內(nèi)容。如果你不知道 axios 是什么,不用擔(dān)心,我們會(huì)慢慢解釋的。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>學(xué)習(xí)在vue中使用axios</title>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
</div>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
Vue.createApp({
el: '#app',
data(){
return {
message: 'Hello Axios',
}
},
mounted(){
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => console.log(response))
.catch(error => console.log(error))
}
}).mount('#app')
</script>
</body>
</html>
在 node項(xiàng)目中導(dǎo)入axios組件。
$ npm install axios
在vue3 中使用axios獲得數(shù)據(jù)的例子。
<script setup>
import { onMounted } from 'vue';
import axios from 'axios'
onMounted(() => {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then((response) => console.log(response))
.catch((error) => console.log(error));
});
</script>
<template>
<div >
<div>業(yè)務(wù)內(nèi)容一覽</div>
</template>
2 axios方法
??axios處理方法分為同步處理與異步處理兩種,axios默認(rèn)的是異步處理方法。獲得的數(shù)據(jù)結(jié)果在下面幾個(gè)方法中進(jìn)行處理。
axios.get('/user?ID=12345')
.then(function (response) {
// 描述axios處理成功后要處理什么
console.log(response);
})
.catch(function (error) {
// 描述axios處理出錯(cuò)時(shí)要做什么
console.log(error);
})
.finally(function () {
// 無(wú)論axios的處理結(jié)果如何,都會(huì)執(zhí)行
});
在 Vue 實(shí)例中使用 axios 中g(shù)et,post ,delete,put方法創(chuàng)建數(shù)據(jù)遠(yuǎn)程連接。
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.delete(url[, config])
axios.head(url[, config])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
??返回json對(duì)象在 response.data
的屬性中獲得數(shù)據(jù)內(nèi)容, response 包含的其他內(nèi)容不僅是數(shù)據(jù),還有status、headers、statusText、config。如果只關(guān)注狀態(tài),可以看到如果使用 GET 方法處理成功則返回狀態(tài)碼 200,使用 POST 方法返回狀態(tài)碼 201。
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
console.log(response.data)//數(shù)據(jù)內(nèi)容
console.log(response.status)
console.log(response.headers)
console.log(response.statusText)
console.log(response.config)
})
.catch(error => console.log(error))
}
1 axios 異步方法
通過(guò)異步方法獲得數(shù)據(jù)列表,在將列表中的數(shù)據(jù)內(nèi)容顯示到模板v-for指令中。
<script setup>
import {ref,onMounted } from 'vue';
import axios from 'axios'
const userlist=ref([]);
onMounted(() => {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then((response) => userlist.value=response.data)
.catch((error) => console.log(error));
});
</script>
<template>
<div class="m-4 p-4" style="height:97vh;overflow-y:auto">
<div>業(yè)務(wù)內(nèi)容一覽</div>
<div v-for="list in userlist ">
id:{{list.id}} name:{{list.name}}
</div>
</div>
</template>
2 axios 同步方法
??Composition API 中使用了 async 和 await 設(shè)置的函數(shù)為同步函數(shù)。很多業(yè)務(wù)都需要axios 同步方法來(lái)處理,我們將axios處理函數(shù)設(shè)置關(guān)鍵字async 和 await,這個(gè)函數(shù)就是同步函數(shù)。
同步處理關(guān)鍵字 async , await
<script setup>
import {ref,onMounted } from 'vue';
import axios from 'axios'
const userlist=ref([]);
// 使用 async 和 await 函數(shù)定義同步關(guān)鍵字
onMounted(async () => {
try {
const response = await axios.get(
'https://jsonplaceholder.typicode.com/users'
);
userlist.value=response.data
} catch (error) {
console.log(error);
}
});
</script>
<template>
<div class="m-4 p-4" style="height:97vh;overflow-y:auto">
<div>業(yè)務(wù)內(nèi)容一覽</div>
<div v-for="list in userlist ">
id:{{list.id}} name:{{list.name}}
</div>
</div>
</template>
??普通方法設(shè)置成同步方法。
<script setup>
import {ref,onMounted } from 'vue';
import axios from 'axios'
const userlist=ref([]);
onMounted( () => {
init();
});
//定義同步方法
const init =async () => {
try {
const response = await axios.get(
'https://jsonplaceholder.typicode.com/users'
);
userlist.value=response.data
} catch (error) {
console.log(error);
}
}
</script>
<template>
<div class="m-4 p-4" style="height:97vh;overflow-y:auto">
<div>業(yè)務(wù)內(nèi)容一覽</div>
<div v-for="list in userlist ">
id:{{list.id}} name:{{list.name}}
</div>
</div>
</template>
3 創(chuàng)建實(shí)例與配置攔截器
???您可以使用 create 方法創(chuàng)建一個(gè) axios 實(shí)例??梢栽?create 方法的參數(shù)中設(shè)置 baseURL,headers表頭信息等其他url請(qǐng)求設(shè)置。axios 實(shí)例
<script setup>
import {ref,onMounted} from 'vue';
import axios from 'axios'
const userlist=ref([]);
onMounted( () => {
init();
});
const headers = {
Authorization: `Bearer`
}
const init =async () => {
const instance = axios.create({
baseURL:'https://jsonplaceholder.typicode.com/users',
headers: headers
});
const response = await instance.get();
userlist.value=response.data
}
</script>
<template>
<div class="m-4 p-4" style="height:97vh;overflow-y:auto">
<div>業(yè)務(wù)內(nèi)容一覽</div>
<div v-for="list in userlist ">
id:{{list.id}} name:{{list.name}}
</div>
</div>
</template>
配置攔截器
??攔截器可以在 axios 發(fā)送請(qǐng)求之前或從服務(wù)器返回響應(yīng)時(shí)對(duì) Request 和 Response 對(duì)象進(jìn)行業(yè)務(wù)處理的監(jiān)聽(tīng)方法。
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.interceptors.request.use((config) => {
console.log(config)
return config;
});
//在攔截器中設(shè)置 baseURL
axios.interceptors.request.use((config) => {
config.baseURL = 'https://test.com';
console.log(config)
return config;
});
在瀏覽器中可以看到 baseURL 已被覆蓋。顯示錯(cuò)誤消息,因?yàn)闊o(wú)法訪問(wèn) https://test.com這個(gè)url地址。
axios.interceptors.response.use((response) => {
console.log(response);
return response;
});
??Response 可用于在認(rèn)證失敗并返回狀態(tài)碼401(Unauthorized)時(shí)候,作認(rèn)證失敗時(shí)的注銷處理。通過(guò)檢查每個(gè)響應(yīng)的狀態(tài)碼,可以根據(jù)每個(gè)代碼進(jìn)行不同的業(yè)務(wù)處理。
axios.interceptors.response.use(
(response) => response,
(error) => {
if (error.response.status === 401) {
//logout 注銷處理
}
return Promise.reject(error);
}
);
4 axios 插件plugins
??創(chuàng)建一個(gè) axios.js 文件,在文件中定義一個(gè)axios插件plugins功能。插件中允許我們?cè)O(shè)置一個(gè)共通的 baseURL方法路徑,項(xiàng)目中使用axios方法可以直接引用到這個(gè)公共url路徑。
axios.js
import axios from 'axios';
const axiosPlugin = {
install(app, options) {
const axiosInstance = axios.create({
baseURL: options.baseURL,
});
app.provide('axios', axiosInstance);
},
};
export default axiosPlugin;
main.js
項(xiàng)目中vue組件引入axiosPlugin插件功能,插件中引入一個(gè)共通的baseURL: 'https://jsonplaceholder.typicode.com/'訪問(wèn)路徑。
import { createApp } from 'vue'
import router from './router'
import App from './App.vue'
import axiosPlugin from './axios';
const app = createApp(App)
app.use(router)
app.use(axiosPlugin, {
//所有axios訪問(wèn)路徑頭
baseURL: 'https://jsonplaceholder.typicode.com/'
});
app.mount('#app')
axios使用文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-729662.html
??在vue組件中獲得inject 過(guò)濾方法,設(shè)置每個(gè)axios對(duì)象訪問(wèn)url的時(shí)候都要通過(guò)inject方法過(guò)濾訪問(wèn)的url地址。所有的地址baseURL+ 后臺(tái)系統(tǒng)的業(yè)務(wù)路徑文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-729662.html
<script setup>
import {ref,onMounted } from 'vue';
import { inject } from 'vue';
const axios = inject('axios');
const userlist=ref([]);
onMounted( () => {
init();
});
const init=async ()=>{
//訪問(wèn)地址是 'https://jsonplaceholder.typicode.com/'+ '/users'
const response = await axios.get('/users');
console.log(response.data);
userlist.value=response.data;
}
</script>
<template>
<div class="m-4 p-4" style="height:97vh;overflow-y:auto">
<div>業(yè)務(wù)內(nèi)容一覽</div>
<div v-for="list in userlist ">
id:{{list.id}} name:{{list.name}}
</div>
</div>
</template>
到了這里,關(guān)于Vue3最佳實(shí)踐 第六章 Pinia,Vuex與axios,VueUse 4(axios)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!