abortNavigation
只能在 路由中间件处理程序 中使用。
Type
ts
abortNavigation(err?: Error | string): false
Parameters
err
- Type:
Error
|string
Optional error to be thrown byabortNavigation
.
示例
下面的示例显示了如何在路由中间件中使用 abortNavigation
来防止未经授权的路由访问:
middleware/auth.ts
ts
export default defineNuxtRouteMiddleware((to, from) => {
const user = useState('user')
if (!user.value.isAuthorized)
return abortNavigation()
return navigateTo('/edit-post')
})
err
作为一个字符串
您可以将错误作为字符串传递:
middleware/auth.ts
ts
export default defineNuxtRouteMiddleware((to, from) => {
const user = useState('user')
if (!user.value.isAuthorized)
return abortNavigation('Insufficient permissions.')
})
err
作为错误对象
You can pass the error as an Error
object, e.g. caught by the catch
-block:
middleware/auth.ts
ts
export default defineNuxtRouteMiddleware((to, from) => {
try {
/* code that might throw an error */
}
catch (err) {
return abortNavigation(err)
}
})