content
1. Introduce the vue-router instance into the index.js file in the router
3. Mount the global navigation guard
Application scenario : The login page prevents the user page from accessing other pages directly in the address bar;
Background : Entering the address in the address bar can access other pages; however, we need a system to intercept;
That is to intercept the global navigation guard, which is implemented by the method of the vue-Router instance;
1. Introduce the vue-router instance into the index.js file in the router
import Router from 'vue-router'
Vue.use(Router)
2. Create a routing instance
const router = new Router({
routes: [
{ path: '/', redirect: '/login' },
{ path: '/login', component: Login },
{ path: '/home', component: Home}
]
})
3. Mount the global navigation guard
//全局路由前置守卫 --路由拦截
router.beforeEach((to, from, next) => {
// to 将要前往的路由
//from 从哪个路由过来的
//next(path) 是一个函数 表示继续执行下一步,强制执行前往的path 路由
//如果前往login 页面 则不需要token 直接进入就可以
if (to.path === "/login") return next();
//获取token
const TOKEN = window.sessionStorage.getItem("TOKEN");
if (!TOKEN) {
//token 不存在 name 意味着 没有进行登录 返回登录页面
next({ path: "/login" });
}
//已经 存在TOKEN name 就可以进行
next();
});