曦远 (DealiAxy)一份私人的文字刊物

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 分钟

StarBlog博客开发笔记:前端开发(8)之vuex与状态管理

状态管理 在很多应用场景下,我们需要在组件之间共享状态,比如我们的左侧导航栏需要收缩和展开的功能,收缩状态时宽度很小,只显示菜单图标,因为导航菜单栏收缩之后宽度变了,所以右侧的主内容区域要占用导航栏收缩的空间,主内容区域宽度也要根据导航栏的收缩状态做变更,而导航栏和主内容区域是两个不同的组件,而非父子组件之间不支持状态传递,所以组件之间的状态共享问题发生了。 之前我写flutter的时候,响应式设

2023-07-14 · StarBlog前端开发-Vue · 约 1 分钟

讨论

共 0 条

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

加载评论中…