编程导航
除了使用 <router-link> 创建用于声明式导航的锚点标签外,我们还可以使用路由器的实例方法以编程方式执行此操作。
导航到不同的位置
注意:以下示例将路由器实例称为 router。在组件内部,您可以使用 $router 属性访问路由器,例如 this.$router.push(...)。如果您使用的是组合式 API,则可以通过调用 useRouter() 访问路由器。
要导航到不同的 URL,请使用 router.push。此方法将一个新条目推入历史堆栈,因此当用户单击浏览器后退按钮时,他们将被带回上一个 URL。
这是您单击 <router-link> 时内部调用的方法,因此单击 <router-link :to="..."> 等同于调用 router.push(...)。
| 声明式 | 编程式 |
|---|---|
<router-link :to="..."> | router.push(...) |
参数可以是字符串路径或位置描述符对象。示例
// literal string path
router.push('/users/eduardo')
// object with path
router.push({ path: '/users/eduardo' })
// named route with params to let the router build the url
router.push({ name: 'user', params: { username: 'eduardo' } })
// with query, resulting in /register?plan=private
router.push({ path: '/register', query: { plan: 'private' } })
// with hash, resulting in /about#team
router.push({ path: '/about', hash: '#team' })注意:如果提供了 path,则会忽略 params,而 query 则不会,如上例所示。相反,您需要提供路由的 name 或手动指定包含任何参数的完整 path
const username = 'eduardo'
// we can manually build the url but we will have to handle the encoding ourselves
router.push(`/user/${username}`) // -> /user/eduardo
// same as
router.push({ path: `/user/${username}` }) // -> /user/eduardo
// if possible use `name` and `params` to benefit from automatic URL encoding
router.push({ name: 'user', params: { username } }) // -> /user/eduardo
// `params` cannot be used alongside `path`
router.push({ path: '/user', params: { username } }) // -> /user在指定 params 时,请确保提供 string 或 number(或对于 可重复参数,提供这些类型的数组)。任何其他类型(如对象、布尔值等)将自动转换为字符串。对于 可选参数,您可以提供空字符串 ("") 或 null 作为值将其删除。
由于 prop to 接受与 router.push 相同类型的对象,因此相同的规则适用于两者。
router.push 和所有其他导航方法都返回一个 Promise,它允许我们等待导航完成并了解它是否成功或失败。我们将在 导航处理 中详细讨论这一点。
替换当前位置
它类似于 router.push,唯一的区别是它不会推送新的历史条目进行导航,正如其名称所暗示的那样 - 它替换了当前条目。
| 声明式 | 编程式 |
|---|---|
<router-link :to="..." replace> | router.replace(...) |
也可以直接将属性 replace: true 添加到传递给 router.push 的 to 参数中
router.push({ path: '/home', replace: true })
// equivalent to
router.replace({ path: '/home' })遍历历史记录
此方法接受一个表示在历史堆栈中前进或后退多少步的单个整数作为参数,类似于 window.history.go(n)。
示例
// go forward by one record, the same as router.forward()
router.go(1)
// go back by one record, the same as router.back()
router.go(-1)
// go forward by 3 records
router.go(3)
// fails silently if there aren't that many records
router.go(-100)
router.go(100)历史记录操作
您可能已经注意到,router.push、router.replace 和 router.go 是 window.history.pushState、window.history.replaceState 和 window.history.go 的对应方法,它们确实模仿了 window.history API。
因此,如果您已经熟悉 浏览器历史记录 API,那么在使用 Vue Router 时,操作历史记录会感觉很熟悉。
值得一提的是,Vue Router 导航方法 (push、replace、go) 在创建路由器实例时传递的 history 选项无论是什么,都能始终如一地工作。