在router中创建一个导航守卫
// 导航守卫通过login页面判断有无token值,没有就一直在login页面 router.beforeEach((to,from,next)=>{ if (to.path== '/login') { next() }else { let token = window.sessionStorage.getItem('token') if (!token) { next('/login') }else{ next() } } })
现在会使登录页面进不去,所以要在登录页中请求一个token值,让守卫放行即可
Login.vue
submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { this.$api.login({ // 传两个参数用户和密码 username: this.ruleForm.username, password: this.ruleForm.password }).then(res => { console.log(res.data); this.getLogin(res.data) window.sessionStorage.setItem('token',res.data.token); this.$router.push('/') //跳转到首页 }) } else { console.log('error submit!!'); return false; } }); },
重定向到welcom
