美文网首页
nuxt路由拦截问题2019-01-18

nuxt路由拦截问题2019-01-18

作者: 坨坨_ea46 | 来源:发表于2019-01-18 18:31 被阅读0次

    问题场景: 页面登录之前,其他页面是没有权限访问的。
    做法:
    1. 在plugins文件夹下创建auth.js.

    export default ({ app }) => {
      app.router.beforeEach((to, from, next) => {
        if (process.client) {
          const token = sessionStorage.getItem('token');
          if (!token && to.path !== '/login') {
            next('/login');
          } else if (to.path !== '/login') {
              next();
          } else {
            next();
          }
        }
      });
    };
    
    1. nuxt.config.js页面
    plugins: [
        '@/plugins/auth',
      ],
    

    这种做法存在问题:1. next('/login');会走error页面,如图;


    image.png

    解决方案:

    1. 在middleware文件夹下创建redirect.js.
    export default function ({ route, redirect }) {
      if (process.client) {
        const token = sessionStorage.getItem('token');
        if (!token && route.path !== '/login') {
          redirect('/login');
        }
      }
    }
    
    1. nuxt.config.js页面
      router: {
        middleware: ['redirect'],
      },
    

    注意: nuxt1版本的时候plugins的方法是没有报错的,这个有待研究。

    相关文章

      网友评论

          本文标题:nuxt路由拦截问题2019-01-18

          本文链接:https://www.haomeiwen.com/subject/nufodqtx.html