Vue封裝axios的示例講解
1、axios:是一個(gè)基于Promise的網(wǎng)絡(luò)請(qǐng)求庫。既可以在node.js(服務(wù)器端)使用,也可以在瀏覽器端使用
(1)在node.js中使用的原生的http模塊
(2)在瀏覽器中使用的XMLHttpRequest
2、vue中的使用方法
(1)安裝:npm install axios
(2)引用方法:
原生的方式(不推薦使用)
axios({ url:'http://127.0.0.1:9001/students/test', //遠(yuǎn)程服務(wù)器的url method:'get', //請(qǐng)求方式 }).then(res=>{ this.students = res.data }).catch(e=>{ console.error(e); }) //缺點(diǎn):每個(gè)使用axios的組件都需要導(dǎo)入
注:axios對(duì)服務(wù)端數(shù)據(jù)的封裝
- res.config:響應(yīng)信息的配置情況
- res.data:響應(yīng)的數(shù)據(jù)
- res.headers:響應(yīng)頭信息(信息的大小、信息的類型)
- res.request:請(qǐng)求對(duì)象
- res.status:請(qǐng)求、響應(yīng)的狀態(tài)碼
- res.statusText:請(qǐng)求、響應(yīng)狀態(tài)碼對(duì)應(yīng)的文本信息
在項(xiàng)目的main.js文件中導(dǎo)入axios,將其寫入Vue的原型中(推薦使用)
import axios from "axios"; Vue.prototype.$http = axios
在組件中通過this.$http的方式使用
this.$http.get('http://127.0.0.1:9001/students/test').then(res=>{ this.students = res.data }).catch(e=>{ console.log(e) })
缺點(diǎn):只能在vue2使用,vue3中不能用
將axios單獨(dú)封裝到某個(gè)配置文件中(在配置文件中單獨(dú)封裝axios實(shí)例)
(1)配置文件:axiosApi.js
import axios from "axios"; const axiosApi = axios.create({ baseURL:'http://127.0.0.1:9001', //基礎(chǔ)地址 timeout:2000 //連接超時(shí)的時(shí)間(單位:毫秒) }) export default axiosApi //axiosApi是axios的實(shí)例
(2)使用:
import $http from '../config/axiosapi' $http.get('/students/test').then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
優(yōu)點(diǎn):既可以在vue2中使用,也可以在vue3中使用
3、axios的不同請(qǐng)求方式向服務(wù)器提交數(shù)據(jù)的格式:
(1)get請(qǐng)求:服務(wù)器端通過req.quert參數(shù)名來接收
直接將請(qǐng)求參數(shù)綁定在url地址上
let str = '張三' $http.get('/students/test/?username='+str).then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
通過params方式進(jìn)行提交
let str = '張三' $http.get('/students/test',{ params:{ username:str } }).then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
(2)post方式請(qǐng)求:服務(wù)器端通過req.body.參數(shù)名獲取數(shù)據(jù)
let str = '張三' $http.post('/students/test',{ username:str }).then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
(3)put方式請(qǐng)求:和post方式一樣
(4)delete方式請(qǐng)求:和get方式一樣
到此這篇關(guān)于Vue封裝axios的示例講解的文章就介紹到這了,更多相關(guān)Vue axios內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue全局共享數(shù)據(jù)之globalData,vuex,本地存儲(chǔ)的使用
這篇文章主要介紹了Vue全局共享數(shù)據(jù)之globalData,vuex,本地存儲(chǔ)的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10