VUE零基礎入門axios的使用
一.axios是什么
axios是一款ajax請求工具,是一個用于發(fā)送ajax請求的HTTP庫,本質(zhì)上是對AJAX的封裝。而且Axios支持 Promise操作, 讓我們無需再使用傳統(tǒng)callback方式來進行異步編程。(Promise 是JS中進行異步編程的一種解決方案。)
二.axios的特點
- 前后端都可以使用
- 不依賴dom
- 攔截擴展強大
- 可封裝復用性強
三.axios怎么安裝
win+R 找到cmd命令窗口 切換到項目目錄(cd 項目目錄)
輸入npm i axios -S
然后運行項目

四.在VUE全局掛載
分為三步
在 main.js中
導入
import axios from 'axios';
掛載
Vue.prototype.$axios = axios;

使用
在App.vue中
this .$axios.xxx
舉個栗子:

五.axios便捷方法
post(url , data , config)
get(url , config) get 傳遞參數(shù)給后端
?參數(shù)名=參數(shù)值&參數(shù)名2=參數(shù)值2?current=2
.delete(url,config) 刪除
.put(url,data,config) 修改
六.axios基礎方法
語法如下:
axios({
url,//請求的地址
methods//請求方法 get,post,put,delete
data,post請求的數(shù)據(jù)
params:get請求的數(shù)據(jù)
headers:請求頭配置
})
七.axios執(zhí)行結果
語法如下:
網(wǎng)絡請求成功
.then(res=>{
res.data 請求返回的數(shù)據(jù)
}
請求失敗
.catch(err=>{
err.response.data 返回失敗數(shù)據(jù)
}
舉個栗子:
this.$axios.get('/api/feed?current=' + this.current
, {
headers: {
"Authorization": 'Bearer ' + localStorage.getItem('token')
}
},
)
.then(res => {
console.log('成功', res.data);
this.feedList = res.data.data;
this.pagnation = res.data.pagnation;
})
.catch(err => {
console.error(err);
alert(err.response.data.msg)
})八.config axios 配置
給 headers: 請求頭 添加token
headers: {
"Authorization": 'Bearer ' + localStorage.getItem('token')
}切記:'Bearer '要加空格
或者在main.js中直接配置
// 給每個請求都攔截下來 添加請求的token信息
axios.interceptors.request.use(function(config) {
config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
return config
})九.restFul
可觀看視頻了解
1.接口設計風格
2.強調(diào)每個url地址都是一個資源
3.可以通過get,post,put,delete操作資源
4.get獲取 post新增 put修改 delete刪除
九.如何審查元素
在網(wǎng)絡里

網(wǎng)絡下面的載荷

網(wǎng)絡下面的預覽

應用中

到此這篇關于VUE零基礎入門axios的使用的文章就介紹到這了,更多相關VUE axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3子組件上綁定(v-model="xx")父組件傳過來的值后報錯解決
這篇文章主要給大家介紹了關于vue3子組件上綁定(v-model="xx")父組件傳過來的值后報錯解決辦法,文中通過示例代碼介紹的非常詳細,對大家學習或者使用vue3具有一定的參考學習價值,需要的朋友可以參考下2023-07-07

