vue中的路由导航
//引入路由组件
import router from 'router'
// beforeEach 全局前置守卫
// to 代表去哪里 是一个路由对象 from 从哪里来
// next 为一个函数
router.beforeEach((to, form.next) => {
// 判断加载地址是否为 /home开头的
if (to.path.startWith('/home')) {
//如果是 再去判断token
if (token存在) {
next() // 放行
}
else {
//否则返回login页面
next('/login')
}
} else {
// 不是'/home开头的地址 放行'
next()
}
})
// 路由后置守卫
router.afterEach(() => {
})
// 导出 router 模块
export default router
axios拦截请求
// 引入所需组件
import axios from 'axios'
import router from 'router组件'
// 大数字处理
import jsonBigInt from 'json-bigInt'
// 设置baseURL
axios.defaults.baseURL = '接口统一地址'
// 响应预处理函数 then catch 之前
// 进行大数字处理
axios.defaults.transformResponse = [function (data) {
return jsonBigInt.parse(data)
}]
// 拦截处理 请求拦截
axios.interceptors.request.use(function (config) {
// config 为默认请求配置 与传入请求配置得到结合
// 必须return
// 添加统一请求头
config.headers['Authorization'] = '请求头参数'
return config
}), function (error) {
// 请求失败处理
return Promise.reject(error)
}
// 响应拦截器
axios.interceptors.response.use(function (response) {
return response
}), function (error) {
// 捕获异常状态码
let status = error.response.status
if (status === 404) {
// 页面找不到
}
// else if ....
// ——————————————————————————————分割线————————————————————————————————————————————————————————————
// 如果在异常函数里处理错误 但是没有将当前的错误截取到的话 那么依然不会进入到then 还需要catch捕获
// 这时我们直接返回一个 promise对象 表示错误已经被处理 相当于强行截止错误
return new Promise(function () { })
}
// 当初axios
export default axios
// 在main.js 中将axios挂载vue实例上
Vue.prototype.$axios = axios