如何禁用特定页面中的中间件,nuxt 中间件 [英] how to disable middleware in specific page, nuxt middleware
问题描述
// in nuxt.config.js =>
router: {
middleware: ['role']
},
// in middleware/role.js =>
export default function ({app}) {
if (!window.localStorage.getItem('auth.token')) {
//app.router.push('/auth/login');
console.log('middleware');
}
}
// in login.vue =>
export default {
role: false,
}
// in root page =>
export default {
role: false,
middleware({app}){
if (!window.localStorage.getItem('auth.token')) {
app.router.push('/auth/login');
}
},
}
当令牌为空并重定向用户时,页面会一次又一次地加载,所以我评论此重定向并控制台记录一条消息,以检查发生了什么.此角色中间件正在加载角色中间件设置为 false 的页面上.检查下图.
when token is empty and redirect user, the page is loading again and again so i comment this redirect and console log a message, to check what happen. this role middleware is loading on that page where the role middleware is set to false. check the image below.
在这里你可以看到中间件打印了两次,一个用于 root('/'),另一个用于登录页面(这里我禁用了角色中间件).如何禁用此登录页面的中间件.
here you can see middleware printed twice, one for root('/') and another one for login page (here i disabled role middleware). how to disable this middleware to this login page.
推荐答案
你可以使用这个
middleware({ route }) {
if (!['do-not-run-here', 'public-page', 'index'].includes(route.name)) return
// all your cool code here
console.log('passed')
},
如果这是一个您不想拥有中间件的页面,您可以快速返回.在我的示例中,我们确实检查了路线的名称,如果它是 do-no-run-here
、public-page
或 index
中间件根本不在那里执行.
当然,如果你想确定页面的名称,设置一个 name
属性是好的.
You can have some quick return in case this is a page you don't want to have a middleware. In my example, we do check the name of the route, and if it's do-no-run-here
, public-page
or index
the middleware is simply not executed there.
Of course, setting a name
prop is good if you want to be sure of the name of the page.
在所有其他中间件上,中间件将运行得非常好.没有 middleware: false
如果它是您要找的东西.
On all the other ones, the middleware will run perfectly fine. There is no middleware: false
if it's what you were looking for.
另一种解决方案是对某些页面使用特定的 layout
,并在其上放置中间件.并且不要将这个用于您不想安装中间件的页面.
An alternative solution would be to use a specific layout
for some pages, with the middleware on it. And not use this one for the pages you don't want to have the middleware on.
这篇关于如何禁用特定页面中的中间件,nuxt 中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!