Vue路由跳转方式

169 阅读1分钟

声明式导航

1. <router-link :to="...">

router-link 组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 a 标签,可以通过配置 tag 属性生成别的标签.

不带参数:

<!-- 通过name(建议使用) -->
<router-link :to="{name: 'home'}">
<!-- 通过path -->
<router-link :to="{path: '/home'}">

携带参数:

query 传参(类似get,参数显示在URL后面)

<router-link :to="{name:'home', query: {a: 1}}">
跳转页面获取参数:

html中:

$route.query.a

script中:

this.$route.query.a

params 传参(类似post)

<!-- 如果提供了path,params会被忽略,所以只能通过name -->
<router-link :to="{name:'home', params: {b: 2}}">
需要路由配置

router.js:

path: "/home/:b" 
跳转页面获取参数:

html中:

$route.params.b

script中:

this.$route.params.b

2. <router-link :to="..." replace>

用法和 <router-link :to="..."> 一样
区别:

<router-link :to="...">会向history中添加新记录,点击浏览器后退按钮时,会回到上一个页面,等同于 window.history.pushState <router-link :to="..." replace>不会向history中添加新记录,而是会替换掉当前的history记录,等同于 window.history.replaceState

编程式导航

1. router.push(...)

不带参数:

//通过name
this.$router.push({name: 'home'})
//通过path
this.$router.push({path: '/home'})
//简写
this.$router.push('/home')

携带参数:

query 传参(类似get,参数显示在URL后面)

this.$router.push({name:'home', query: {a: 1}})
this.$router.push({path:'/home', query: {a: 1}})
跳转页面获取参数:

html中:

$route.query.a

script中:

this.$route.query.a

params 传参(类似post)

//如果提供了path,params会被忽略,所以只能通过name
this.$router.push({name:'home', params: {b: 2}})
需要路由配置

router.js:

path: "/home/:b" 
跳转页面获取参数:

html中:

$route.params.b

script中:

this.$route.params.b

2. router.replace(...)

用法和 router.push(...) 一样
区别:

router.push(...)会向history中添加新记录,点击浏览器后退按钮时,会回到上一个页面,等同于 window.history.pushState router.replace(...)不会向history中添加新记录,而是会替换掉当前的history记录,等同于 window.history.replaceState

3. router.go(n)

参数n是一个整数,指定在history中前进或后退n步,等同于window.history.go(n)
//在history中前进一步,等同于router.forward()
this.$router.go(1)
//在history中后退一步,等同于router.back()
this.$router.go(-1)
//刷新当前页面
this.$router.go(0)

4. router.forward()

在history中前进一步,等同于router.go(1)

5. router.back()

在history中后退一步,等同于router.go(-1)

总结:

router-link 当被点击后,内部会立刻把 to 的值传到 router.push(),等同于调用 router.push()