vue結(jié)合axios實(shí)現(xiàn)restful風(fēng)格的四種請(qǐng)求方式
Axios 是一個(gè)基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中,基本請(qǐng)求有5種:
get:多用來獲取數(shù)據(jù)post:多用來新增數(shù)據(jù)put:多用來修改數(shù)據(jù)(需要傳遞所有字段,相當(dāng)于全部更新)patch:多用來修改數(shù)據(jù),是在put的基礎(chǔ)上新增改進(jìn)的,適用于局部更新,比如我只想修改用戶名,只傳用戶名的字段就ok了,而不需要像put一樣把所有字段傳過去delete:多用來刪除數(shù)據(jù)
axios其實(shí)和原生ajax,jquery中的$ajax類似,都是用于請(qǐng)求數(shù)據(jù)的,不過axios是基于promise的,也是vue官方比較推薦的做法。
那么我們一起來看看具體在vue中的使用吧。
1、npm下載axios到vue項(xiàng)目中
這里解釋一下為什么要下載qs,qs的作用是用來將請(qǐng)求參數(shù)序列化,比如對(duì)象轉(zhuǎn)字符串,字符串轉(zhuǎn)對(duì)象,不要小看它,會(huì)在后面有大用處的。
// npm下載axios到項(xiàng)目中 npm install axios --save // npm下載qs到項(xiàng)目中 npm install qs.js --save
2、main.js里引入
記住這邊使用axios時(shí)定義的名字,我定義的是axios,所以后續(xù)請(qǐng)求我也必須使用axios,當(dāng)然你可以定義其他的,htpp,$axios,哪怕是你的名字都沒關(guān)系,注意規(guī)范。
// 引入axios import axios from 'axios' // 使用axios Vue.prototype.axios = axios; // 引入qs import qs from 'qs' // 使用qs Vue.prototype.qs = qs;
3、定義全局變量路徑(不是必須的,但是推薦)
(1)、方法一
可在main.js里定義
// 右邊就是你后端的每個(gè)請(qǐng)求地址公共的部分 // * : 地址是我瞎編的,涉及隱私,大家只要把每個(gè)請(qǐng)求地址一樣的公共部分提出來即可 Vue.prototype.baseURL = "http://127.0.0.1:9000/api";
(2)、方法二
在config中的dev.env和prod.env中配置,在main.js里使用那兩個(gè)文件的變量即可
①dev.env:本地環(huán)境
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
// 這里是本地環(huán)境的請(qǐng)求地址(請(qǐng)忽略地址,明白原理即可)
API_ROOT: ' "http://localhost:8080/web" '
})②prod.env:上線環(huán)境
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
// 這里是本地環(huán)境的請(qǐng)求地址(請(qǐng)忽略地址,明白原理即可)
API_ROOT: ' "http://localhost:8080/web" '
})③main.js中使用此路徑
Vue.prototype.baseURL = process.env.API_ROOT;
4、在具體需求的地方使用
舉個(gè)例子:
當(dāng)我在登錄頁面點(diǎn)擊登錄,然后需要請(qǐng)求后臺(tái)數(shù)據(jù)判斷登錄是否能通驗(yàn)證,以此來判斷是否能正常登錄,請(qǐng)求方法我寫在methods里了,通過vue的@click點(diǎn)擊事件,當(dāng)點(diǎn)擊登錄按鈕發(fā)起請(qǐng)求,然后通過vue的v-model綁定用戶名和密碼文本框的值,用來獲取用戶輸入的值以便獲取發(fā)送參數(shù)
之前我定義的變量是axios,所以這邊使用this.axios發(fā)起請(qǐng)求,post是請(qǐng)求方式,而我需要把用戶名和密碼以字符串的形式發(fā)送,所以需要qs序列化參數(shù)(qs不是必須的,具體根據(jù)你請(qǐng)求發(fā)送的參數(shù)和后端定義的參數(shù)格式匹配即可)
- .
then是請(qǐng)求成功后的回調(diào)函數(shù),response包含著后端響應(yīng)的數(shù)據(jù),可以打印看看 - .
catch是請(qǐng)求失敗后的捕獲,用來校驗(yàn)錯(cuò)誤
login() {
this.axios.post('http://bt2.xyz:8083/login/checkAdmin', qs.stringify({
"username": this.userinfo.username,
"password": this.userinfo.password
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}以上方法也可以這樣寫:
login() {
this.axios({
method:"post",
url:"http://bt2.xyz:8083/login/checkAdmin",
data:qs.stringify({
"username": this.userinfo.username,
"password": this.userinfo.password
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}注 : get、delete請(qǐng)求的參數(shù)是params(特殊情況可以直接跟在地址后面),而post、put、patch的參數(shù)是data
下面我們看看四種具體的請(qǐng)求方式吧 (忽略地址,涉及隱私所以就輸了假的地址):
這里的${this.baseURL}就是我們前面定義的全局路徑,只要在后面跟上變化的地址即可
這里的headers和qs不是必須的,因?yàn)槲覀儤I(yè)務(wù)需要傳遞這些數(shù)據(jù),所以我才寫的,大家只是參考格式即可
這里給出每種請(qǐng)求的兩種寫法,不盡相同,所以具體的請(qǐng)求還得看業(yè)務(wù)需求
put請(qǐng)求用的比較多,patch我自己用的很少,但是原理都是一樣的,這里就不多說了
使用箭頭函數(shù)是為了不改變this指向,方便后期處理數(shù)據(jù)
(1)、get
this.axios({
method: "get",
url:`${this.baseURL}/GetAll`,
headers: {
Account: "Admin",
Password:"123456"
}
})
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error);
});this.axios.get('http://bt2.xyz:8083/solr/adminQuery', {
params: {
"page": 1,
"rows": 5
}
})
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error);
});(2)、post
this.axios({
method:"post",
url:`${this.baseURL}/Create`,
headers: {
Account: "Admin",
Password:"123456"
},
data:qs.stringify({
Title: this.addTitle,
Host: this.addHost,
Port: this.addPort,
Account: this.addAccount,
Password: this.addPassword,
DbName: this.addDbName
})
})
.then( (response)=> {
console.log(response);
})
.catch(function (error) {
console.log(error);
});login() {
this.axios.post('http://bt2.xyz:8083/login/checkAdmin', qs.stringify({
"username": this.userinfo.username,
"password": this.userinfo.password
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}(3)、put
像這個(gè)請(qǐng)求,我就在地址欄后面追加了一個(gè)參數(shù),id,只要后端格式允許,也可以這樣做
this.axios({
method:"put",
url:`${this.baseURL}/Update/`+(this.Data[index].id),
headers: {
Account: "Admin",
Password:"123456"
},
data:qs.stringify({
Title: inputs[0].value,
Host: inputs[1].value,
Port: inputs[2].value,
Account: inputs[3].value,
Password: inputs[4].value,
DbName: inputs[5].value
})
})
.then( (response)=> {
console.log(response);
})
.catch(function (error) {
console.log(error);
});this.axios.put('http://bt2.xyz:8083/Goods/update', {
"goodsId": goodsId,
"goodsName": goodsName,
"goodsPrice": goodsPrice,
"goodsNum": goodsNum,
"goodsKind": 1,
"goodsWeight": goodsWeight
})
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error);
});(4)、delete
this.axios({
method:"delete",
url:`${this.baseURL}/Delete/`+(this.Data[index].id),
headers: {
Account: "Admin",
Password:"123456"
}
})
.then((response)=> {
console.log(error);
})
.catch((error)=> {
console.log(error);
});this.axios.delete('http://bt2.xyz:8083/Goods/delete?goodsId=' + this.ProductId)
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error);
});以上就是常用的四種restful風(fēng)格的請(qǐng)求,都是博主自己開發(fā)中請(qǐng)求的數(shù)據(jù),都沒問題,但是具體的請(qǐng)求還要看大家和后端數(shù)據(jù)格式的規(guī)范以及一些業(yè)務(wù)熟悉,這里只提供思路。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。希望大家多多支持腳本之家。
切記跨域問題,記得讓后端處理,如果是本地的話,可以參考vue的代理
這里附上axios的官方文檔,提供大家參考。axios中文官方文檔
相關(guān)文章
Vue實(shí)現(xiàn)登錄記住賬號(hào)密碼功能的思路與過程
最近在學(xué)習(xí)vue,發(fā)現(xiàn)了vue的好多坑,下面這篇文章主要給大家介紹了關(guān)于Vue實(shí)現(xiàn)登錄記住賬號(hào)密碼功能的思路與過程,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-11-11
詳解vue與后端數(shù)據(jù)交互(ajax):vue-resource
本篇文章主要介紹了詳解vue與后端數(shù)據(jù)交互(ajax):vue-resource,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-03-03
vue中解決chrome瀏覽器自動(dòng)播放音頻和MP3語音打包到線上的實(shí)現(xiàn)方法
這篇文章主要介紹了vue中解決chrome瀏覽器自動(dòng)播放音頻和MP3語音打包到線上的實(shí)現(xiàn)方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
Vue.js中Line第三方登錄api的實(shí)現(xiàn)代碼
這篇文章主要介紹了Vue.js中Line第三方登錄api實(shí)現(xiàn)代碼,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
淺談Vue2.4.0 $attrs與inheritAttrs的具體使用
這篇文章主要介紹了淺談Vue2.4.0 $attrs與inheritAttrs的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Vue?監(jiān)視屬性之天氣案例實(shí)現(xiàn)
這篇文章主要介紹了Vue?監(jiān)視屬性之天氣案例實(shí)現(xiàn),文章以天氣為例展開介紹Vue?監(jiān)視屬性?的相關(guān)內(nèi)容,需要的小伙伴可以參考一下2022-05-05

