更改路线的拍击者事件 [英] Sapper event for route change

查看:181
本文介绍了更改路线的拍击者事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未通过身份验证,则需要将其重定向到登录页面.理想情况下,我需要Vue.js中的route.beforeEach之类的东西:

I need to redirect users to login page if they are not authenticated. I need something like route.beforeEach in Vue.js, ideally:

sapper.beforeRouteChange((to, from, next) => {

  const isAuth = "[some session or token check]";

  if (!isAuth) {
    next('/login')
  }

  next()
})

我找到了 Sapper-受保护的路由(路由卫士),但我认为这还不足以满足我的需求.如果令牌或身份验证在运行时发生更改怎么办?还是被反应性所覆盖?

I found Sapper - protected routes (route guard) this question but I think it's not enough for my needs. What if token or auth changes in runtime? OR is it covered by reactivity?

我认为 Sapper GitHub上的问题解决了我的问题.

Edit 1: I think that this issue on Sapper GitHub solves my problem.

推荐答案

所以我将这段代码放在了/src/routes/_layout.svelte:

So I placed this code to /src/routes/_layout.svelte:

  import AuthMiddleware from "../methods/authMiddleware.js";
  import { goto, stores } from '@sapper/app';
  const { page } = stores();

  if (typeof window !== "undefined" && typeof document !== "undefined") {
    page.subscribe(({ path, params, query }) => {
      const from = window.location.pathname;
      const redirect = (href) => { goto(href); }

      AuthMiddleware.beforeChange(from, path, redirect, params, query);
    })
  }

这是authMiddleware.js文件:

export default class AuthMiddleware {

  static beforeChange(from, to, redirect, params, query) {

    if (!AuthMiddleware._isUserAuthenticated()) {
      redirect("/login");
    }
  }

  // ~

  static _isUserAuthenticated() {
    return true; // TODO: Implement
  }
}

有关路线钩子的更多信息,请点击此处

more information on route hooks can be found here

  • https://github.com/sveltejs/sapper/issues/30
  • https://sapper.svelte.dev/docs/#Stores

这篇关于更改路线的拍击者事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆