一、声明式 与 编程式导航
1.1 导航到不同的位置
声明式 | 编程式 | 描述 |
---|---|---|
<router-link to="..."></router-link> | 【选项式API】:this.$router.push(...) 【组合式API】: useRouter().push(...) | 会向 history 栈(浏览器的路由栈) 中添加一个新的记录,所以,当用户点击浏览器回退按钮时,会回到之前的 URL |
- ❗提示:
- 编程式的
router.push(...)
的语法:- 其参数可以是一个字符串,或者是一个描述地址的对象;
- 如果参数是描述地址的对象的话,其对象中的
path
和params
不能同时使用;
- 编程式的
- 注意:
path
和query
配合使用;query
可以是个对象,但是它的属性值不能是对象;
name
和params
配合使用;params
可以是个对象,但他的属性值不能为对象;- 使用
name
的时候,需要对对应组件的path
进行改造;- 语法:
/path/:参数名1/:参数名2/:...
;
- 语法:
- ❌ 写成对象的形式:
- 示例展示:
- 选项式API:
this.$router.push('/guoMan') // 简单的字符串地址 this.$router.push({ path : '/guoMan' }) // 路径地址对象 path(路由地址) this.$router.push({ name : 'guoMan' }) // 路径地址对象 name(路由名称) // --------------------- 嵌套路由 ------------------------- this.$router.push('/guoMan/GuoManList') // 简单的字符串地址 this.$router.push({ path : '/guoMan/guoManList' }) // 路径地址对象 path(路由地址) this.$router.push({ name : 'guoManList' }) // 路径地址对象 name(路由名称) // --------------------- 路径传参 ------------------------- const id_one = 110 const id_two = 119 const id_three = 120 this.$router.push(`/guoMan/${ id_one }`) // 简单的字符串地址 this.$router.push({ path : `/guoMan/${ id_two }`}) // 路径地址对象 path(路由地址) this.$router.push({ name : 'guoMan' , params: { id_three } }) // 路径地址对象 name(路由名称)
- 组合式API:
import { useRouter } from 'vue-router' const router = useRouter() // ==================================================================== router.push('/guoMan') // 简单的字符串地址 router.push({ path : '/guoMan' }) // 路径地址对象 path(路由地址) router.push({ name : 'guoMan' }) // 路径地址对象 name(路由名称) // --------------------- 嵌套路由 ------------------------- router.push('/guoMan/guoManList') // 简单的字符串地址 router.push({ path : '/guoMan/guoManList' }) // 路径地址对象 path(路由地址) router.push({ name : 'guoManList' }) // 路径地址对象 name(路由名称) // --------------------- 路径传参 ------------------------- const id_one = 110 const id_two = 119 const id_three = 120 router.push(`guoMan/${ id_one }`) // 简单的字符串地址 router.push({ path : `/guoMan/${ id_two }`}) // 路径地址对象 path(路由地址) router.push({ name : 'guoMan' , params: { id_three } }) // 路径地址对象 name(路由名称)
- 选项式API:
- 示例展示:
1.2 替换当前位置
声明式 | 编程式 | 描述 |
---|---|---|
<router-link to="xxx" replace></router-link> | 【选项式】this.$router.replace(...) 【组合式】 useRouter().replace(...) | 作用类似于push(...) 唯一不同的是:它在导航时不会向history 栈中添加新纪录,只是取代了当前的条目 |
- 注意:
- 也可以在
router.push(...)
的参数中采用路径地址对象,其路径地址对象中增加一个属性replace: true
;
- 也可以在
1.3 路由历史
选项式 | 组合式 | 描述 |
---|---|---|
this.$router.go(n) | useRouter().go(n) | 该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步 |
- 注意:
router.go(1)
:前进1
条记录,相当于router.forword()
;router.go(-1)
:后退1
条记录,相当于router.back()
;- 如果前进或者后退的步数大与实际的历史记录数,则什么都不会发生;