Vue路由跳转方式

Vue路由跳转方式

声明式导航

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: {a1}})
this.$router.push({path:'/home'query: {a1}})
跳转页面获取参数:

html中:

$route.query.a

script中:

this.$route.query.a

params 传参(类似post)

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

router.js:

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

html中:

$route.params.b

script中:

this.$route.params.b

2. router.replace(...)

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

router.push(...)会向history中添加新记录,点击浏览器后退按钮时,会回到上一个页面,等同于 window.history.pushStaterouter.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()


原文始发于微信公众号(前端24):Vue路由跳转方式

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/217176.html

(0)
李, 若俞的头像李, 若俞

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!