返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
StarBlog前端开发-Vue

StarBlog Blog Development Notes: Frontend Development - Navigation Guards

The router object provides us with the beforeEach method, which allows us to perform certain processing before each route change, also known as navigation guards. Here, we will implement some auxiliary features similar to authentication using navigation guards. Modify the router/index.js file to add navigation guards that check if the user session has expired during each route change. If the login is valid and the user is navigating to the login page, redirect directly to the homepage; if it is a non-login page and the session has expired, redirect to the login page to require login. The code is as follows router.beforeEach

曦远 (DealiAxy)约 4 分钟

The router object provides us with the beforeEach method, which allows you to perform certain operations before each route change. Also known as navigation guards, we'll use them here to implement auxiliary features like authentication.

Modify the router/index.js file to add a navigation guard that checks whether the user's session has expired on every route change. If the login is valid and the user is navigating to the login page, redirect them directly to the homepage. If they're trying to access a non-login page but their session has expired, redirect them to the login page to authenticate.

The code is as follows:

router.beforeEach((to, from, next) => {
  // After successful login on the login page, user information is saved in the session.
  // Its lifetime is tied to the session, becoming invalid when the page is closed.
  let userName = sessionStorage.getItem('user')
  if (to.path === '/login') {
    // If accessing the login page and user session info exists, meaning already logged in, redirect to the homepage
    if (userName) next({path: '/'})
    else next()
  } else {
    if (!userName) {
      // If accessing a non-login page and user session info doesn't exist, meaning not logged in, redirect to the login page
      next({path: '/login'})
    }
  }
})

_EOF_

StarBlog Blog Development Notes: Frontend Development - Navigation Guards

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

StarBlog博客开发笔记:前端开发(2)之页面路由

前言 Vue.js使用虚拟DOM处理单页面,然后使用Webpack打包。通过第5章的示例,读者也许已经发现,无论语法和写法如何不同,Vue.js程序打包后都是一个单一的HTML文件,同时会引入一个标准的JavaScript文件。 Vue.js中编写的所有代码都被Webpack自动打包成可以被浏览器解析的HTML和JavaScript代码,并且项目本身就只有一个页面。这意味着所有的用户对服务器发出进

2024-12-11 · StarBlog前端开发-Vue · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…

StarBlog Blog Development Notes: Frontend Development - Navigation Guards · StarBlog