vue路由跳转时,判断是否登录及权限验证
1、router.js路由内部写法
// 将vueRouter设置为vue的插件
Vue.use(VueRouter)
const router = new VueRouter({
// 指定hash属性与组件的对应关系
routes: [
{ path: '/', component:institution },
{ path: '/login', component:login },
{ path: '/register', component:register },
{ path: '/forget', component:forget },
{ path: '/home', component:home, meta:{auth: true}},//添加字段判断该页面是否需要登录
{ path: '/tips', component:tips, meta:{auth: true}},
{ path: '/consult', component:consult, meta:{auth: false}}
]
})
// 路由守卫
router.beforeEach((to,from,next)=>{
// to要跳转到的路径
// from从哪个路径来
// next往下执行的回调
// 在localStorage中获取token
let token=localStorage.getItem('userName')
// 判断该页面是否需要登录
if(to.meta.auth){
// 如果token存在直接跳转
if(token){
next()
}else{
// 否则跳转到login登录页面
next({
path:'/login',
// 跳转时传递参数到登录页面,以便登录后可以跳转到对应页面
query:{
redirect:to.fullPath
}
})
}
}else{
// 如果不需要登录,则直接跳转到对应页面
next()
}
})
2、在main.js中引入router.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from "./route/index"
import VueRouter from "vue-router"
Vue.use(VueRouter);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3、在login.vue登录页面中进行相应判断,根据登录状态及所接收参数判断登录之后是否需要跳转到对应页面
<template>
<div>
<input type="text" placeholder="用户名" v-model="name" />
<input type="password" placeholder="密码" v-model="password" />
<button @click="submit">登录</button>
</div>
</template>
<script>
export default {
data() {
return {
name: "",
password: ""
};
},
created() {},
methods: {
submit() {
//登录成功后存储用户信息
localStorage.setItem("userName", this.name);
localStorage.setItem("passWord", this.password);
// 接收参数,如果存在redirect参数,登录后重定向到指定页面
if (this.$route.query.redirect) {
this.$router.push({ path: this.$route.query.redirect });
// 如不存在,直接跳转到首页
} else {
this.$router.push({ path: "/home" });
}
}
}
};
</script>