vue結(jié)合axios實現(xiàn)restful風(fēng)格的四種請求方式
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中,基本請求有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其實和原生ajax,jquery中的$ajax類似,都是用于請求數(shù)據(jù)的,不過axios是基于promise的,也是vue官方比較推薦的做法。
那么我們一起來看看具體在vue中的使用吧。
1、npm下載axios到vue項目中
這里解釋一下為什么要下載qs,qs的作用是用來將請求參數(shù)序列化,比如對象轉(zhuǎn)字符串,字符串轉(zhuǎn)對象,不要小看它,會在后面有大用處的。
// npm下載axios到項目中 npm install axios --save // npm下載qs到項目中 npm install qs.js --save
2、main.js里引入
記住這邊使用axios時定義的名字,我定義的是axios,所以后續(xù)請求我也必須使用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里定義
// 右邊就是你后端的每個請求地址公共的部分 // * : 地址是我瞎編的,涉及隱私,大家只要把每個請求地址一樣的公共部分提出來即可 Vue.prototype.baseURL = "http://127.0.0.1:9000/api";
(2)、方法二
在config中的dev.env和prod.env中配置,在main.js里使用那兩個文件的變量即可
①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)境的請求地址(請忽略地址,明白原理即可) 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)境的請求地址(請忽略地址,明白原理即可) API_ROOT: ' "http://localhost:8080/web" ' })
③main.js中使用此路徑
Vue.prototype.baseURL = process.env.API_ROOT;
4、在具體需求的地方使用
舉個例子:
當(dāng)我在登錄頁面點擊登錄,然后需要請求后臺數(shù)據(jù)判斷登錄是否能通驗證,以此來判斷是否能正常登錄,請求方法我寫在methods里了,通過vue的@click點擊事件,當(dāng)點擊登錄按鈕發(fā)起請求,然后通過vue的v-model綁定用戶名和密碼文本框的值,用來獲取用戶輸入的值以便獲取發(fā)送參數(shù)
之前我定義的變量是axios,所以這邊使用this.axios發(fā)起請求,post是請求方式,而我需要把用戶名和密碼以字符串的形式發(fā)送,所以需要qs序列化參數(shù)(qs不是必須的,具體根據(jù)你請求發(fā)送的參數(shù)和后端定義的參數(shù)格式匹配即可)
- .
then
是請求成功后的回調(diào)函數(shù),response包含著后端響應(yīng)的數(shù)據(jù),可以打印看看 - .
catch
是請求失敗后的捕獲,用來校驗錯誤
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請求的參數(shù)是params(特殊情況可以直接跟在地址后面),而post、put、patch的參數(shù)是data
下面我們看看四種具體的請求方式吧 (忽略地址,涉及隱私所以就輸了假的地址):
這里的${this.baseURL}就是我們前面定義的全局路徑,只要在后面跟上變化的地址即可
這里的headers和qs不是必須的,因為我們業(yè)務(wù)需要傳遞這些數(shù)據(jù),所以我才寫的,大家只是參考格式即可
這里給出每種請求的兩種寫法,不盡相同,所以具體的請求還得看業(yè)務(wù)需求
put請求用的比較多,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
像這個請求,我就在地址欄后面追加了一個參數(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)格的請求,都是博主自己開發(fā)中請求的數(shù)據(jù),都沒問題,但是具體的請求還要看大家和后端數(shù)據(jù)格式的規(guī)范以及一些業(yè)務(wù)熟悉,這里只提供思路。如有錯誤或未考慮完全的地方,望不吝賜教。希望大家多多支持腳本之家。
切記跨域問題,記得讓后端處理,如果是本地的話,可以參考vue的代理
這里附上axios的官方文檔,提供大家參考。axios中文官方文檔
相關(guān)文章
vue-cli3+typescript新建一個項目的思路分析
這篇文章主要介紹了vue-cli3+typescript新建一個項目的思路,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08vue directive全局自定義指令實現(xiàn)按鈕級別權(quán)限控制的操作方法
這篇文章主要介紹了vue directive全局自定義指令實現(xiàn)按鈕級別權(quán)限控制,本文結(jié)合實例代碼對基本概念做了詳細(xì)講解,需要的朋友可以參考下2023-02-02vue自定義loader將行內(nèi)樣式px轉(zhuǎn)rem適配
這篇文章主要為大家介紹了vue自定義loader將行內(nèi)樣式px轉(zhuǎn)rem適配示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08VUE3+TS遞歸組件實現(xiàn)TreeList設(shè)計實例詳解
這篇文章主要為大家介紹了VUE3+TS遞歸組件實現(xiàn)TreeList設(shè)計實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09淺談vue-props的default寫不寫有什么區(qū)別
這篇文章主要介紹了淺談vue-props的default寫不寫有什么區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08