vue项目
login.vue登陆界面:使用Element-UI的form表单验证+正则表达式验证表单,通过验证后,通过接口发送表单数据到后台,返回token存在localStorage中,
//封装
function setToken (val, name = 'token') {
window.localStorage.setItem(name, val)
}
//返回操作
setToken(res.data.token)
并且跳转到首页home.vue。运用生命周期钩子函数—创建后created ,判断如果有token直接跳转到首页
created () {
if (getToken()) {
this.$router.push('/home')
}
}
使用axios拦截器中的请求拦截器,如果请求中有token,则请求中添加token,
instance.interceptors.request.use(function (config) {
// 请求拦截器中,如果有token,请求中添加token
if (getToken()) {
config.headers.token = getToken()
}
return config
}
响应拦截器中,根据返回的状态码,执行对应操作,如果状态码为200则不做处理,如果为其他,则根据饿了么消息
提示组件,返回错误信息
Message.error(response.data.message)
在首页home.vue中,运用生命周期钩子函数—创建后created钩子,如果没用token,跳转回首页,
if (!getToken()) {
this.$router.push('/')
return
}
之后再根据token,发送请求获取用户信息,存在vuex中,以便全局调用,之后的页面就暂时不说了
this.$store.state.userInfo = this.userInfo