「Vue」登陆-路由拦截器
1、main.js设置拦截器
router.beforeEach(function (to,from,next) { if (to.meta.requireAuth) { if (store.state.token) { next() } else { next({name: 'log',query: {backUrl: to.fullPath}}) } }else( next() ) })
2、路由设置
{ path: '/course',component: Course,meta: { requireAuth: true}}
3、vue页面方法设置,对应main.js设置的backUrl
login() { this.$axios.post('api/login/',{user:this.user,pwd:this.pwd}).then(ret => { if (ret.data.code === 1000) { var obj = {token:ret.data.token,name:ret.data.data} this.$store.commit('getToken',obj) var url = this.$route.query.backUrl if (url) { this.$router.push({path: url}) } else { this.$router.push({name:'home'}) } } if (ret.data.code === 1001) { alert('用户名或密码错误') } if (ret.data.code === 1002) { alert('请求错误') } }).catch(ret => { console.log(ret) }) this.user = '' this.pwd = '' }