- A+
axios?是一個(gè)基于promise用于瀏覽器和?nodejs?的?HTTP?客戶端,這篇文章主要介紹了Vue中axios的基本用法及axios的特征和使用注意細(xì)節(jié),本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
1.什么是axios?
axios 是一個(gè)基于promise用于瀏覽器和 nodejs 的 HTTP 客戶端。簡單的理解就是ajax的封裝
2.axios的特征
從瀏覽器中創(chuàng)建 XMLHttpRequest
從 node.js 發(fā)出 http 請求
支持 Promise API
攔截請求和響應(yīng)
轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
取消請求
自動轉(zhuǎn)換JSON數(shù)據(jù)
客戶端支持防止 CSRF/XSRF
3.axios在使用的時(shí)候需要注意的細(xì)節(jié)
引用 axios 時(shí) Vue.prototype.axios = axios Vue.prototype.$axios = axios Vue.prototype.$http = axios 其實(shí)是都一個(gè)東西,只是vue的原型鏈上加個(gè)變量(且變量不同),值是axios對象 。
只是 一個(gè)是jquery封裝過的異步調(diào)用方法 一個(gè)是vue推薦的第三方異步封裝方法 他們都是調(diào)用的axios對象
只是調(diào)用的時(shí)候 axios.post({..}) this.$axios.post({...}) this.$http.post({....})
4.axios在vue中的實(shí)例運(yùn)用(留言評論接口)
App.vue代碼
<template>
<div>
<h1>學(xué)習(xí)axios</h1>
<div v-if="token">
{{userInfo.name}} 積分:{{userInfo.score}} 等級:{{userInfo.rank}}
<button @click="logout">退出</button>
</div>
<div class="login" v-else>
<h3>登錄</h3>
用戶名: <input type="text" v-model="user.name"> <br>
密碼: <input type="password" v-model="user.password"> <br>
<button @click="login">登錄</button>
</div>
<div>
<h3>添加留言</h3>
<textarea rows="" cols="" v-model="msg">
</textarea> <br>
<button @click="sendMsg">發(fā)表留言</button>
</div>
<div class="list" v-if="feedlist.length">
<div class="item" v-for="item in feedlist" :key="item.id">
<h5>{{item.name}}</h5>
<p>{{item.msg}}</p>
<p>{{item.date}}</p>
<hr>
</div>
</div>
<!-- pagnation.pageTotal 如果有分頁信息就顯示,沒有就隱藏 -->
<div class="pagnation" v-if="pagnation.pageTotal">
<!-- 如果current小等于就disabled 按鈕不可以用 -->
<button :disabled="current<=1" @click="current--;getFeed()">上一頁</button>
<!-- 循環(huán)遍歷總分頁書 出現(xiàn)1,2,3,4 -->
<!-- 如果current等于item 就是當(dāng)前頁給一個(gè)active的class -->
<!-- 單擊時(shí)候設(shè)置current,獲取分頁對應(yīng)的評論列表信息 -->
<span :class="{'active':current==item}" v-for="item in pagnation.pageTotal" :key="item"
@click="current=item;getFeed()">{{item}}</span>
<!-- 如果current大于等于總分頁數(shù)據(jù) 按鈕不可以用 -->
<button :disabled="current>=pagnation.pageTotal" @click="current++;getFeed()">下一頁</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
msg: '', //需要添加的評論
current: 1, //默認(rèn)獲取第一頁評論
feedlist: [], //笑話列表
pagnation: {
}, //分頁信息
user: {
name: '',
password: '',
},
// 從本地獲取用戶信息 parse 把json字符串轉(zhuǎn)換為js對象
userInfo: JSON.parse(localStorage.getItem("userInfo") || "{}"), //用戶信息,
// 從本地獲取token,字符串不需要pase轉(zhuǎn)
token: localStorage.getItem("token"), //token
}
},
// 組件創(chuàng)建完畢就加載
created() {
this.getFeed();
},
// 登錄后顯示用戶信息
methods: {
sendMsg() {
// 基礎(chǔ)方法
this.$axios({
url: "/api/feed",
method: "post",
data: {
msg: this.msg
}
})
.then(res => {
// alert(res.data.msg);
if (res.data.code == 0) {
// 讓頁面回歸第一1
this.current = 1;
// 獲取評論列表
this.getFeed();
// 清空評論框
this.msg = '';
}
})
},
// 登錄成功后,獲取評論信息
// 除了登錄與注冊,接口規(guī)定向服務(wù)器請求數(shù)據(jù)必須加上 請求頭token
// token一串加密的字符,包含了用戶信息等..(后端靠token識別用戶是否登錄)
getFeed() {
this.$axios.get(
"/api/feed?current=" + this.current, //請求url
// {
// headers:{
// "Authorization":'Bearer '+localStorage.getItem("token")
// }
// }
)
// 網(wǎng)絡(luò)請求成功
.then(res => {
console.log("成功", res.data)
this.feedlist = res.data.data; //評論信息
// 更新分頁信息
this.pagnation = res.data.pagnation; //分頁信息
})
// 網(wǎng)絡(luò)請求失敗
.catch(err => {
console.log("失敗", err);
alert(err.response.data.msg)
})
},
logout() {
// 清空用戶信息與token
this.userInfo = {};
this.token = null;
// 移除本地存儲
localStorage.removeItem("userInfo");
localStorage.removeItem("token");
},
login() {
// 實(shí)現(xiàn)登錄
this.$axios.post(
"/api/login", //請求的地址
this.user, //請求的數(shù)據(jù)
)
.then(res => {
// 網(wǎng)絡(luò)請求成功
if (res.data.code === 200) {
// res是響應(yīng)的數(shù)據(jù)
// 01 本地存用戶信息,與token
// stringify 把js對象轉(zhuǎn)換為json字符串
localStorage.setItem("userInfo", JSON.stringify(res.data.user))
localStorage.setItem("token", res.data.token);
// 02 更新userInfo與token
this.userInfo = res.data.user;
this.token = res.data.token;
// 登錄成功 獲取評論
this.getFeed()
} else {
alert(res.data.msg);
}
})
.catch(err => {
// 網(wǎng)絡(luò)請求失敗
console.error(err)
})
}
}
}
</script>
<style>
.active {
color: #FF7700
}
.pagnation span {
padding: 15px;
cursor: pointer;
}
</style>
mian.js代碼
import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false // 導(dǎo)入axios 沒有./ (axios網(wǎng)絡(luò)請求工具:1不依賴dom,2.前后端都可以用,3. 豐富攔截,擴(kuò)展功能,4可封裝,復(fù)用性強(qiáng)) import axios from 'axios'; // 掛載到vue的全局(原型上),在每個(gè)組件都可以使用 ,prototype是固定的,$axios是自定義的 Vue.prototype.$axios = axios; // 指定默認(rèn)的請求域名 axios.defaults.baseURL = "http://dida100.com:8888" // 給每個(gè)請求攔截一下,添加請求Token信息 axios.interceptors.request.use(function(config){ config.headers.Authorization = 'Bearer '+localStorage.getItem("token"); return config; }) // interceptors 攔截器 // request 請求 // config 配置 // headers頭信息 // Authorization 權(quán)限 // defaults 默認(rèn) // baseURL 基礎(chǔ)URL new Vue({ render: h => h(App), }).$mount('#app')
到此這篇關(guān)于Vue中axios的基本用法的文章就介紹到這了

