封装axios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| import axios from "axios"
const BASE_URL = "example.com"
const instance = axios.create({ baseURL : BASE_URL, timeout : 8000 })
instance.interceptors.request.use((req)=>{ const headers = req.headers if(!headers.Authorization)headers.Authorization = "Bear lnpbqc"
return req })
const LOGIN_INVALID = 6789 import router from "./router"
instance.interceptors.response.use((resp)=>{ const {code,data,msg} = resp.data
if(code==200){ return data }else if(code==LOGIN_INVALID){ setTimeout(()=>{router.push("/login")},3000) return Promise.reject("登录失效") }else{ return Promise.reject(msg||"其他错误") } })
function request(options){ options.method = options.method || "get" if(options.method.toLowerCase()=='get')options.params = options.data return instance(options) }
['get','post','patch','delete','put'].forEach((item)=>{ request[item] = (url,data,options)=>{ return request({ url, data, method:item, ...options }) } })
export default request
|
用法为 request({url,method,data})
或者 request.get(url,data,options)
([post,delete,put,patch]可选)
封装storage
虽然自带的api能用,但不好用
如要使用localStorage存储的值,以字符串来存储,所以在存取对象的时候还需要对其进行手动json的序列化和反序列化
而且本例使用了类似命名空间的方法来隔离一个网站的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const NAMESPACE = "lnpbqc"
export default { setItem(key,val){ const storage = this.getStorage() storage[key] = val this.updateStorage(storage) }, getItem(key){ return this.getStorage()[key] }, clearItem(key){ const storage = this.getStorage() delete storage[key] this.updateStorage(storage) }, clearAll(){ window.localStorage.clear() }, getStorage(){ return JSON.parse(window.localStorage.getItem(NAMESPACE) || '{}') } updateStorage(obj){ window.localStorage.setItem(NAMESPACE,JSON.stringfy(obj)) } }
|
还可以封装成localStorage
和sessionStorage
不同的存储方式,还能在外面使用自定义命名空间,最后得到这样的效果:
this.storage().local().namespace("lnpbqc").getItem("abc")