前言
ajax相信不用過多介紹了,作者堅信可以用配置解決的問題,請勿硬編碼,下面話不多說了,來一看看詳細的介紹吧。
姊妹篇 jQuery進階:用最優雅的方式寫ajax請求
axios是Vue官方推薦的ajax庫, 用來取代vue-resource。更多詳細的基礎知識可以參考這篇文章://www.gxlcms.com/article/109444.htm
優點:
1. content-type配置
// filename: content-type.js module.exports = { formData: 'application/x-www-form-urlencoded; charset=UTF-8', json: 'application/json; charset=UTF-8' }
2. api 配置
// filename: api-sdk-conf.js import contentType from './content-type' export default { baseURL: 'http://192.168.40.231:30412', apis: [ { name: 'login', path: '/api/security/login?{{id}}', method: 'post', contentType: contentType.formData, status: { 401: '用戶名或者密碼錯誤' } } ] }
3. request.js 方法
// request.js import axios from 'axios' import qs from 'qs' import contentType from '@/config/content-type' import apiConf from '@/config/api-sdk-conf' var api = {} // render 函數用來渲染路徑上的變量, 算是一個微型的模板渲染工具 // 例如render('/{{userId}}/{{type}}/{{query}}', {userId:1,type:2, query:3}) // 會被渲染成 /1/2/3 function render (tpl, data) { var re = /{{([^}]+)?}}/ var match = '' while ((match = re.exec(tpl))) { tpl = tpl.replace(match[0], data[match[1]]) } return tpl } // fire中的this, 會動態綁定到每個接口上 function fire (query = {}, payload = '') { // qs 特別處理 formData類型的數據 if (this.contentType === contentType.formData) { payload = qs.stringify(payload) } // 直接返回axios實例,方便調用then,或者catch方法 return axios({ method: this.method, url: render(this.url, query), data: payload, headers: { contentType: this.contentType } }) } apiConf.apis.forEach((item) => { api[item.name] = { url: apiConf.baseURL + item.path, method: item.method, status: item.status, contentType: item.contentType, fire: fire } }) export default api
4. 在組件中使用
import api from '@/apis/request' ... api.login.fire({id: '?heiheihei'}, { username: 'admin', password: 'admin', namespace: '_system' }) ...
瀏覽器結果:
Request URL:http://192.168.40.231:30412/api/security/login??heiheihei Request Method:POST Status Code:200 OK Remote Address:192.168.40.231:30412 Referrer Policy:no-referrer-when-downgrade POST /api/security/login??heiheihei HTTP/1.1 Host: 192.168.40.231:30412 Connection: keep-alive Content-Length: 47 Accept: application/json, text/plain, */* Origin: http://localhost:8080 contentType: application/x-www-form-urlencoded; charset=UTF-8 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 Content-Type: application/x-www-form-urlencoded Referer: http://localhost:8080/ Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 username=admin&password=admin&namespace=_system
5. 更多
有個地方我不是很明白,希望懂的人可以給我解答一下
如果某個組件中只需要login方法,但是我這樣寫會報錯。
import {login} from '@/apis/request'
這樣寫的前提是要在request.js最后寫上
export var login = api.login
但是這是我不想要的,因為每次增加一個接口,這里都要export一次, 這不符合開放閉合原則,請問有什么更好的方法嗎?
總結
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com