登录鉴权、路由守卫

211 阅读1分钟

本文中的实例,是神舟记账项目的。

登录跳转

用户在某一个界面,因为JWT过期或其他原因导致,登录失效,弹出提示是否重新登录,并跳转到登录页面,待登录成功以后再跳转回到之前的页面(return_to)。涉及到跨页面使用变量return_to,有以下几种方案可以实现:本地存储LocalStorage、查询参数queryString、状态管理vuexpinia。这也是面试题,有哪些可以存储的地方,在页面切换(路由切换,而不是真正的刷新页面)的时候,存储的内容还能够保持不变。

// SignInPage.tsx
const router = useRouter();
const onSubmit = async (e:Event)=>{
  e.preventDefault()
  if(!hasError(errors)){
    const response = await http.post<{jwt:string}>('/session', formData)
    localStorage.setItem('jwt', response.data.jwt)
    const returnTo = route.query.return_to?.toString();
    router.push(returnTo || '/')
  }
}
  • 以上代码就实现了登录页面就自动跳转到之前的页面。

跳过广告

用户登录成功后默认会到根路径,也就是welcome页面,用户第2天重新打开app时,不需要再看一遍广告而直接跳过,也就是点击跳过或完成时在本地记录一下localStorage

  • 封装跳过广告组件
// SkipFeatures.tsx
import { defineComponent } from "vue";
import { RouterLink } from "vue-router";

export const SkipFeatures = defineComponent({
  setup: (props, context) => {
    const onClick = () => {
      localStorage.setItem("skipFeatures", "yes");
    };
    return () => (
      <span onClick={onClick}>
        <RouterLink to="/items">跳过</RouterLink>
      </span>
    );
  },
});
  • 使用SkipFeatures组件
export const FirstActions:FunctionalComponent = ()=>{
    return <div class={s.actions}>
      <SkipFeatures class={s.fake} />
      <RouterLink to="/welcome/2">下一页</RouterLink>
      <SkipFeatures to="/start" />
}

路由守卫

  • 如果看过广告就不用看了,给每一个路由添加守卫
// routes.tsx

export const routes: RouteRecordRaw[] = [
  { path: "/", redirect: "/welcome" },
  { path: "/welcome",
    component: () => import("../views/Welcome"),
    beforeEnter: (to, from, next) => {
      // 如果用户点击过跳转,就直接跳到items
      localStorage.getItem("skipFeatures") === "yes" ? next("/items") : next();
  },
]