How to assign a middleware to specific group of routes?

对着背影说爱祢 提交于 2020-06-17 09:33:33

问题


let's say I had this block of route, so far I only knew that middleware could be assigned through nuxt-config.js (globally) or per route (independently)

pages

 - index.vue
 - goSomeWhere.vue
 - goThisWay.vue
 - admin
    - index.vue
    - goThere.vue
    - goHere.vue

I want to assign a middleware just for every /admin routes, so is there another approach that might be suitable for me?


回答1:


Certainly the most concise way to verify a block of routes is to use a global middleware that targets any route starting with /admin.

You could set up a file inside the middleware folder that defines the redirects you need depending on the conditions. Obviously you want to block any admin route from someone who isn't logged in as an admin level user. To do this you should set any admin user in your store with a property such as "admin" or if you need to set levels you could assign a value of admin1, admin2 etc. For the sake of simplicity lets say any authorized user who logs in has a property admin = true; set in their user object in the store.

You should then create a file in the middleware folder, let's call it 'auth.js':

export default function ({store, redirect, route}) {

  const userIsAdmin = !!store.state.user.admin;
  const urlRequiresAuth = /^\/admin(\/|$)/.test(route.fullPath)
  if (urlRequiresAuth && !userIsAdmin) {
      return redirect('/')
  }
  return Promise.resolve
}

This simply checks if the user has admin set to true and if the requested route requires auth. It will redirect to your index page if the user is not authorized.

You will need to register your middleware file in nuxt.config.js:

...

router: {
  middleware: ['auth'];
},

...

And you should be good to go.



来源:https://stackoverflow.com/questions/62332813/how-to-assign-a-middleware-to-specific-group-of-routes

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