Sapper event for route change

徘徊边缘 提交于 2020-01-25 06:47:32

问题


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()
})

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?

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


回答1:


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);
    })
  }

And this is authMiddleware.js file:

export default class AuthMiddleware {

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

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

  // ~

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


来源:https://stackoverflow.com/questions/58691278/sapper-event-for-route-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!