1.router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home'
Vue.use(VueRouter)
const routes = [
{ path: '/', redirect: '/login' },
{ path: '/login', component: Login },
{ path: '/home', component: Home }
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
// to 将要访问的路径 from 代表从哪个路径跳转而来 next 是一个函数,表示放行
// next() 放行 next('/login') 强制跳转
if (to.path === '/login') return next()
const tokenStr = window.sessionStorage.getItem('token')
if (!tokenStr) return next('/login')
next()
})
export default router
2.components/Home.vue
<template>
<div>
<el-button type="info" @click="logout">退出</el-button>
</div>
</template>
<script>
export default {
methods: {
logout () {
window.sessionStorage.clear() // 清空token
this.$router.push('/login') // 返回登录页面
}
}
}
</script>
<style lang="less" scoped>
</style>