NUXT 3在中间件中使用可复合
我想通过检查用户是否已登录来守护一条路线,但是:
- 我无法阅读可合价的值,
- 我不确定我的中间件是否合适。
我的组合:
// composable/useAuth.js
const useAuth = () => {
// user login, sign out, sign up logic
const isLoggedIn = () => {
return !!user.value
}
return {
isLoggedIn
}
}
export default useAuth
中间件:
// middleware/check-admin.js
export default defineNuxtRouteMiddleware((to, from) => {
const { isLoggedIn } = useAuth()
console.log(isLoggedIn); // <- Screenshot
if (isLoggedIn) {
return navigateTo(`/albums/${to.params.id}/edit`)
} else {
return navigateTo('/')
}
})
问题:
- 如何从组合物中读取布尔值以通过中间件内的测试?
- 如果用户没有凭据,可以使用
navigateto
中止路由吗?文档说,我可以使用abortnavigation()
I want to guard a route by checking if the user is logged in, but:
- I can't read the composable value,
- I am unsure if my middleware got the right body.
My composable:
// composable/useAuth.js
const useAuth = () => {
// user login, sign out, sign up logic
const isLoggedIn = () => {
return !!user.value
}
return {
isLoggedIn
}
}
export default useAuth
My middleware:
// middleware/check-admin.js
export default defineNuxtRouteMiddleware((to, from) => {
const { isLoggedIn } = useAuth()
console.log(isLoggedIn); // <- Screenshot
if (isLoggedIn) {
return navigateTo(`/albums/${to.params.id}/edit`)
} else {
return navigateTo('/')
}
})
My console logs a method body. But I expected a falsy or truthy value:
Problems:
- How can I read a boolean value from my composables to pass the test inside the middleware?
- It is okay to use
navigateTo
to abort the routing, if the user got no credentials? The docs says, I can useabortNavigation()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您返回功能,但从未在最后使用
()
调用它。尝试这样做:
使用
值以了解用户要在哪里导航。
如果您不使用中间件文件中的
.global
后缀,则可以选择在组件中使用中间件的位置。You returning function, but never invoke it by using
()
at the end.Try like this:
Use
to
value to know where user want to navigate.You can choose where to use middleware in component if you're not using
.global
suffix in middleware file.