Vue中axios的基本用法詳解
1.什么是axios?
axios 是一個基于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在使用的時候需要注意的細(xì)節(jié)
引用 axios 時 Vue.prototype.axios = axios Vue.prototype.$axios = axios Vue.prototype.$http = axios 其實是都一個東西,只是vue的原型鏈上加個變量(且變量不同),值是axios對象 。
只是 一個是jquery封裝過的異步調(diào)用方法 一個是vue推薦的第三方異步封裝方法 他們都是調(diào)用的axios對象
只是調(diào)用的時候 axios.post({..}) this.$axios.post({...}) this.$http.post({....})
4.axios在vue中的實例運用(留言評論接口)
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)前頁給一個active的class -->
<!-- 單擊時候設(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() {
// 實現(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. 豐富攔截,擴展功能,4可封裝,復(fù)用性強)
import axios from 'axios';
// 掛載到vue的全局(原型上),在每個組件都可以使用 ,prototype是固定的,$axios是自定義的
Vue.prototype.$axios = axios;
// 指定默認(rèn)的請求域名
axios.defaults.baseURL = "http://dida100.com:8888"
// 給每個請求攔截一下,添加請求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的基本用法的文章就介紹到這了,更多相關(guān)Vue axios用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3使用拖拽組件draggable.next的保姆級教程
做項目的時候遇到了一個需求,拖拽按鈕到指定位置,添加一個輸入框,這篇文章主要給大家介紹了關(guān)于vue3使用拖拽組件draggable.next的保姆級教程,需要的朋友可以參考下2023-06-06
Vue項目前后端聯(lián)調(diào)(使用proxyTable實現(xiàn)跨域方式)
這篇文章主要介紹了Vue項目前后端聯(lián)調(diào)(使用proxyTable實現(xiàn)跨域方式),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Vue文件如何轉(zhuǎn)換成base64并去除多余的文件類型前綴
這篇文章主要介紹了Vue文件如何轉(zhuǎn)換成base64并去除多余的文件類型前綴問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
Vue的transition-group與Virtual Dom Diff算法的使用
這篇文章主要介紹了Vue的transition-group與Virtual Dom Diff算法的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
vue-cli history模式實現(xiàn)tomcat部署報404的解決方式
這篇文章主要介紹了vue-cli history模式實現(xiàn)tomcat部署報404的解決方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

