原文链接 https://www.cnblogs.com/Alex-Song/p/12784506.html
1、router.js路由内部写法
在这里插入代码片
import Vue from "vue"
import VueRouter from "vue-router"
import Home from "../views/home.vue"
import List from "../views/list.vue"
import Mine from "../views/mine.vue"
import Ex from "../views/ex.vue"
import Maps from "../views/maps.vue"
import Login from "../views/login.vue"
// Vue.use(VueRouter)
// 定义路由
const router= new VueRouter({
routes: [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/list',
name: 'list',
component: List,
meta:{
auth:true//添加字段判断该页面是否需要登录
}
},
{
path: '/mine',
name: 'mine',
component: Mine,
meta:{
auth:false
}
},
{
path: '/ex',
name: 'ex',
component: Ex
},
{
path: '/maps',
name: 'maps',
component: Maps
},
{
path: '/login',
name: 'login',
component: Login
}
]
})
// 路由守卫
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()
}
})
export default router
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>
<style lang="scss">
</style>
原文链接 https://www.cnblogs.com/Alex-Song/p/12784506.html