vue結(jié)合axios實(shí)現(xiàn)restful風(fēng)格的四種請(qǐng)求方式
Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中,基本請(qǐng)求有5種:
get:多用來(lái)獲取數(shù)據(jù)post:多用來(lái)新增數(shù)據(jù)put:多用來(lái)修改數(shù)據(jù)(需要傳遞所有字段,相當(dāng)于全部更新)patch:多用來(lái)修改數(shù)據(jù),是在put的基礎(chǔ)上新增改進(jìn)的,適用于局部更新,比如我只想修改用戶名,只傳用戶名的字段就ok了,而不需要像put一樣把所有字段傳過(guò)去delete:多用來(lái)刪除數(shù)據(jù)
axios其實(shí)和原生ajax,jquery中的$ajax類(lèi)似,都是用于請(qǐng)求數(shù)據(jù)的,不過(guò)axios是基于promise的,也是vue官方比較推薦的做法。
那么我們一起來(lái)看看具體在vue中的使用吧。
1、npm下載axios到vue項(xiàng)目中
這里解釋一下為什么要下載qs,qs的作用是用來(lái)將請(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,哪怕是你的名字都沒(méi)關(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)求地址一樣的公共部分提出來(lái)即可 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)我在登錄頁(yè)面點(diǎn)擊登錄,然后需要請(qǐng)求后臺(tái)數(shù)據(jù)判斷登錄是否能通驗(yàn)證,以此來(lái)判斷是否能正常登錄,請(qǐng)求方法我寫(xiě)在methods里了,通過(guò)vue的@click點(diǎn)擊事件,當(dāng)點(diǎn)擊登錄按鈕發(fā)起請(qǐng)求,然后通過(guò)vue的v-model綁定用戶名和密碼文本框的值,用來(lái)獲取用戶輸入的值以便獲取發(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)求失敗后的捕獲,用來(lái)校驗(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);
});
}以上方法也可以這樣寫(xiě):
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ù),所以我才寫(xiě)的,大家只是參考格式即可
這里給出每種請(qǐng)求的兩種寫(xiě)法,不盡相同,所以具體的請(qǐng)求還得看業(yè)務(wù)需求
put請(qǐng)求用的比較多,patch我自己用的很少,但是原理都是一樣的,這里就不多說(shuō)了
使用箭頭函數(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)求,都是博主自己開(kāi)發(fā)中請(qǐng)求的數(shù)據(jù),都沒(méi)問(wèn)題,但是具體的請(qǐng)求還要看大家和后端數(shù)據(jù)格式的規(guī)范以及一些業(yè)務(wù)熟悉,這里只提供思路。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。希望大家多多支持腳本之家。
切記跨域問(wèn)題,記得讓后端處理,如果是本地的話,可以參考vue的代理
這里附上axios的官方文檔,提供大家參考。axios中文官方文檔
相關(guān)文章
vue項(xiàng)目中icon亂碼的問(wèn)題及解決
這篇文章主要介紹了vue項(xiàng)目中icon亂碼的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
vue-cli3+typescript新建一個(gè)項(xiàng)目的思路分析
這篇文章主要介紹了vue-cli3+typescript新建一個(gè)項(xiàng)目的思路,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08
vue directive全局自定義指令實(shí)現(xiàn)按鈕級(jí)別權(quán)限控制的操作方法
這篇文章主要介紹了vue directive全局自定義指令實(shí)現(xiàn)按鈕級(jí)別權(quán)限控制,本文結(jié)合實(shí)例代碼對(duì)基本概念做了詳細(xì)講解,需要的朋友可以參考下2023-02-02
vue自定義loader將行內(nèi)樣式px轉(zhuǎn)rem適配
這篇文章主要為大家介紹了vue自定義loader將行內(nèi)樣式px轉(zhuǎn)rem適配示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
VUE3+TS遞歸組件實(shí)現(xiàn)TreeList設(shè)計(jì)實(shí)例詳解
這篇文章主要為大家介紹了VUE3+TS遞歸組件實(shí)現(xiàn)TreeList設(shè)計(jì)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
vue導(dǎo)出少量pdf文件實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了vue導(dǎo)出少量pdf文件實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
淺談vue-props的default寫(xiě)不寫(xiě)有什么區(qū)別
這篇文章主要介紹了淺談vue-props的default寫(xiě)不寫(xiě)有什么區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08

