一、axios 的封装
在 src 目录下新建一个 api 文件夹里面放新建 axiosFun.js
文件
import axios from 'axios'
// 配置请求的跟路径
axios.defaults.baseURL = 'http://192.168.1.103:8080/EXAM/'
// 登录请求方法
const userLogin = (method, url, params) => {
return axios({
method: method,
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: params,
traditional: true,
transformRequest: [
function (data) {
let ret = ''
for (const it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}
]
}).then(res => res.data)
}
// 通用公用方法
const getInfo = (method, url, params) => {
return axios({
method: method,
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
USERTOKEN: sessionStorage.getItem('token')
},
data: params,
traditional: true,
transformRequest: [
function (data) {
let ret = ''
for (const it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}
]
}).then(res => res.data)
}
export {
userLogin,
getInfo
}
再统一封装一个 用户所有请求操作的文件userOpe.js
与axiosFun.js
在同一文件夹
二、axios 请求拦截器
三、记住账号密码操作
在src 文件夹中 新建一个 util 文件夹 ,在此文件夹中 util.js
,封装相关cookie操作
/**
* 时间戳
* @param {*} timestamp 时间戳
*/
const timestampToTime = (timestamp) => {
const date = new Date(timestamp) // 时间戳为10位需*1000,时间戳为13位的话不需乘1000
const Y = date.getFullYear() + '-'
const M =
(date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
const D =
(date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
const h =
(date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
const m =
(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
':'
const s =
date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return Y + M + D + h + m + s
}
/**
* 设置cookie
**/
function setCookie (name, value, day) {
const date = new Date()
date.setDate(date.getDate() + day)
document.cookie = name + '=' + value + ';expires=' + date
}
/**
* 获取cookie
**/
function getCookie (name) {
const reg = RegExp(name + '=([^;]+)')
const arr = document.cookie.match(reg)
if (arr) {
return arr[1]
} else {
return ''
}
}
/**
* 删除cookie
**/
function delCookie (name) {
setCookie(name, null, -1)
}
/**
* 导出
**/
export {
setCookie,
getCookie,
delCookie
}
四、 挂载路由导航守卫
简单的说,导航守卫就是路由跳转过程中的一些钩子函数。路由跳转是一个大的过程,这个大的过程分为跳转前中后等等细小的过程,在每一个过程中都有一函数,这个函数能让你操作一些其他的事儿的时机,这就是导航守卫。
在router 文件夹中的 index.js 中写