Vue使用axios發(fā)送請求并實現(xiàn)簡單封裝的示例詳解
更新時間:2022年06月30日 14:19:26 作者:什么都干的派森
這篇文章主要介紹了Vue使用axios發(fā)送請求并實現(xiàn)簡單封裝,主要包括安裝axios及簡單使用配置方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
一、安裝axios
npm install axios --save
二、簡單使用
1.配置
main.js中加入如下內(nèi)容
// 引入axios --------------------------------------------------- import axios from 'axios' Vue.prototype.$axios = axios Vue.prototype.$axios.defaults.baseURL = 'http://127.0.0.1:8000/' // 請求根路徑 // -------------------------------------------------------------
2.發(fā)送請求
<1>get
this.$axios.get('index').then(res => { // 返回數(shù)據(jù)在 res.data 中 })
<2>post
this.$axios.post('login', {user:"admin", pwd:"123"}).then(res => { // 返回數(shù)據(jù)在 res.data 中 })
<3>并發(fā)
var res1 = this.$axios.get('index') var res2 = this.$axios.post('login', {user:"admin", pwd:"123"}) this.$axios.all([res1, res2]).then(this.$axios.spread(res1, res2) => { // 兩個請求的返回結(jié)果在 res1 和 res2 中 })
三、封裝使用
1.創(chuàng)建js封裝類
src/request/index.js
// 引入 import Axios from 'axios' import { Message } from 'element-ui' // 需要裝個 element-ui,錯誤提示界面友好一些 // 前端存在 localStorage 中的 token const token = localStorage.getItem('token') // 實例化 const request = Axios.create({ baseURL: "http://127.0.0.1:8000/", // 服務(wù)根路徑 timeout: 200000, // 請求過期時間 headers: { Authorization: token // token 插入請求頭給后端校驗 } }) // 攔截后端返回的請求 request.interceptors.response.use(res => { if (res.status !== 200) { Message.error("something err...") // 返回錯誤的提示信息 } return res.data // 只取 res 中的 data,后續(xù)取值不需要再寫一層 data 了 }) // 導(dǎo)出 export default request
2.配置
main.js中改成如下內(nèi)容
// 引入axios --------------------------------------------------- import request from './request' Vue.prototype.$http = request // -------------------------------------------------------------
3.發(fā)送請求
<1>get
this.$http.get('index').then(res => { // 返回數(shù)據(jù)在 res.data 中 })
<2>post
this.$http.post('login', {user:"admin", pwd:"123"}).then(res => { // 返回數(shù)據(jù)在 res.data 中 })
<3>并發(fā)
var res1 = this.$http.get('index') var res2 = this.$http.post('login', {user:"admin", pwd:"123"}) this.$http.all([res1, res2]).then(this.$http.spread(res1, res2) => { // 兩個請求的返回結(jié)果在 res1 和 res2 中 })
到此這篇關(guān)于Vue使用axios發(fā)送請求并實現(xiàn)簡單封裝的文章就介紹到這了,更多相關(guān)Vue axios發(fā)送請求封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
詳解Vue實戰(zhàn)指南之依賴注入(provide/inject)
這篇文章主要介紹了詳解Vue實戰(zhàn)指南之依賴注入(provide/inject),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11vue+webpack模擬后臺數(shù)據(jù)的示例代碼
這篇文章主要介紹了vue+webpack模擬后臺數(shù)據(jù)的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07