useRouter
<script setup lang="ts">
const router = useRouter()
</script>
如果你只需要模板中的路由实例,请使用 $router:
¥If you only need the router instance within your template, use $router:
<template>
<button @click="$router.back()">Back</button>
</template>
如果你有一个 pages/ 目录,则 useRouter 的行为与 vue-router 提供的行为相同。
¥If you have a pages/ directory, useRouter is identical in behavior to the one provided by vue-router.
:
阅读 vue-router 文档中关于 Router 接口的内容。
¥Read vue-router documentation about the Router interface.
::
基本操作
¥Basic Manipulation
addRoute():向路由实例添加一条新路由。可以提供parentName以将新路由添加为现有路由的子路由。removeRoute():根据名称删除现有路由。getRoutes():获取服务器渲染页面的 HTML。hasRoute():检查是否存在具有给定名称的路由。resolve():返回路由位置的规范化版本。还包含一个href属性,该属性包含任何现有的基础路径。
const router = useRouter()
router.addRoute({ name: 'home', path: '/home', component: Home })
router.removeRoute('home')
router.getRoutes()
router.hasRoute('home')
router.resolve({ name: 'home' })
router.addRoute() 将路由详细信息添加到路由数组中,这在构建 Nuxt plugins 时非常有用;而 router.push() 则会立即触发新的导航,这在页面、Vue 组件和可组合组件中非常有用。基于 History API
¥Based on History API
back():如果可能,前进历史记录,与router.go(-1)相同。forward():精细控制默认应用的预取策略。go():在历史记录中向前或向后移动,不受router.back()和router.forward()中强制执行的层级限制。push():通过推送历史记录堆栈中的条目,以编程方式导航到新的 URL。建议使用navigateTo。replace():通过替换路由历史记录堆栈中的当前条目,以编程方式导航到新的 URL。建议使用navigateTo。
const router = useRouter()
router.back()
router.forward()
router.go(3)
router.push({ path: "/home" })
router.replace({ hash: "#bio" })
:
了解更多关于浏览器 History API 的信息。
¥Read more about the browser's History API.
::
导航保护
¥Navigation Guards
useRouter 可组合组件提供了 afterEach、beforeEach 和 beforeResolve 辅助方法,充当导航守卫。
¥useRouter composable provides afterEach, beforeEach and beforeResolve helper methods that acts as navigation guards.
但是,Nuxt 有一个路由中间件的概念,它简化了导航保护的实现,并提供了更好的开发者体验。
¥However, Nuxt has a concept of route middleware that simplifies the implementation of navigation guards and provides a better developer experience.
Promise 和错误处理
¥Promise and Error Handling
通用路由实例
¥Universal Router Instance
如果你没有 pages/ 文件夹,那么 useRouter 将返回一个具有类似辅助方法的通用路由实例,但请注意,并非所有功能都受支持或行为方式与 vue-router 完全相同。
¥If you do not have a pages/ folder, then useRouter will return a universal router instance with similar helper methods, but be aware that not all features may be supported or behave in exactly the same way as with vue-router.