开发过程中经常会遇到路由跳转需要携带参数的情况,在大多数单页面中,一般都是通过使用vue-router
来实现路由的。通过在Vue实例内部访问$router
来访问路由实例,调用this.$router.push
导航到不同的URL。
注意:
$router
是Vue-router
实例,用$router.push
方法导航到不同的URL
$route
是当前router
跳转对象,获取name、path、query、params等
-
params传参
//传参 this.$router.push({ name: 'testpath', params: { userId: '123' } }) // 这里的 params 不生效 this.$router.push({ path: '/test', params: { userId:'123' } }) //接收参数 this.$route.params.userId
-
query传参
// 带查询参数,变成 /testpath?test=abc this.$router.push({ path: 'testpath', query: { test: 'abc' } }) //接收参数 this.$route.query.test
params传参,只能通过name来引入路由,push里面只有写name才会生效,path不生效,接收参数会是undefined。
区别:
1、params传参不会显示在URL中,query传参会显示在URL中
2、query传参path和name都可以,params只能用name
3、params参数F5强制刷新会被清空