vue-router传递参数3种方法
第一种:get方法
传递值
<router-link :to="{path:'/test',query: { userId: 123,userName:'xia' }}">跳转</router-link>
或
<router-link :to="{name:'test',query: { userId: 123,userName:'xia' }}">跳转</router-link>
接收值(页面刷新的时候不会消失)
this.$route.query.userId // 123
this.$route.query.userName // xia
url上显示参数:http://localhost:8080/test?userId=123&userName=xia
第二种:post方法
传递值
<!-- 必须用 name:'test' -->
<router-link :to="{name:'test',params: { userId: 123,userName:'xia' }}">跳转</router-link>
<!-- 用 path:'/test' 无效 -->
<!-- <router-link :to="{path:'/test',params: { userId: 123,userName:'xia' }}">跳转</router-link> -->
接收值(页面刷新的时候就会消失)
this.$route.params.userId // 123
this.$route.params.userName // xia
url上不显示参数:http://localhost:8080/test
第三种:路由方法
传递值
// router.js
{
path: '/test/:userId/:userName?', //?问号的意思是该参数不是必传项
name: 'test',
component: 'test.vue',
props: true,
},
// App.vue
<router-link to="/test/123/xia">跳转</router-link>
接收值(页面刷新的时候不会消失)
this.$route.params.userId // 123
this.$route.params.userName // xia
url上显示参数:http://localhost:8080/test/123/xia
另外: 如果在链接上设置 replace 属性,当点击时,会调用 router.replace() 而不是 router.push(),于是浏览器不会留下 history 记录。(无法返回到上一页)
<router-link :to="{ path: '/test'}" replace></router-link>
Tips:这里我简单说明下 $router
和 $route
的区别:
$router
:是指整个路由实例,你可以操控整个路由,用法如下:this.$router.go(-1); // 向前或者向后跳转n个页面,n可为正整数或负整数 this.$router.push('/'); // 跳转到指定url路径,history栈中会有记录,点击返回会跳转到上个页面 this.$router.replace('/'); // 跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面
$route
:是指当前路由实例$router
跳转到的路由对象;路由实例可以包含多个路由对象,它们是**父子包含关系**
.// 获取路由传递过来的参数 this.$route.params.userId this.$route.query.userName
本文作者:猫老板的豆
本文链接:https://www.cnblogs.com/bingcola/p/16499210.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步