我清除了isLogin我页面刷新为什么不跳到首页
我页面不清除isLogin存储,从url地址输入login也可以调到登录页面
路由
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
{
path: '/',
redirect: '/login'
},
{
path: '/home',
name: 'Home',
component: () => import('../views/home/home.vue'),
meta: { navShow: true }
},
{
path: '/login',
name: 'Login',
component: () => import('../views/login/Login.vue'),
beforeEach (to, from, next) {
const { isLogin } = sessionStorage
isLogin ? next({ name: 'Home' }) : next()
}
// beforeEach (to, from, next) {
// const isLogin = sessionStorage.isLogin
// if (isLogin) {
// next({ name: 'Home' })
// } else {
// next()
// }
// }
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
// 挂在路由守卫
router.beforeEach((to, form, next) => {
// to 将要访问的路径
// from 代表从哪个路径跳转而来
// next 是一个函数,表示放行
// next() 放行 next('/login') 强制跳转
if (to.path === '/login') return next()
// 获取token
const tokenStr = window.sessionStorage.getItem('isLogin')
console.log(tokenStr)
// if (!tokenStr) return next('/login')
if (!tokenStr) {
next({ name: 'login' })
} else {
next()
}
})
// router.beforeEach((to, from, next) => {
// const { isLogin } = localStorage;
// (isLogin || to.name === 'Login') ? next() : next({ name: 'Login' })
// })
export default router
<script>
import { useRouter } from 'vue-router'
export default {
setup () {
const router = useRouter()
const Loginpage = () => {
sessionStorage.isLogin = true
router.push({ name: 'Home' })
}
return { Loginpage }
}
}
</script>