Vue中$router.push()路由切换、如何传参和获取参数 和获取不到$router.push 参数问题

发布时间 2023-12-28 17:36:30作者: 以后。h

路由的 两种传参方式: 

 一: 声明式

<router-link :to="{ path: '/login' }">Home</router-link>

 

二: 编程式

$router.push(...)  //该方法的参数可以是一个字符串路径,或者一个描述地址的对象。

不带参数写法:

// 字符串(对应填写上面的path)
this.$router.push('/login')

// 对象
this.$router.push({path: '/login'});

// 通过路由的 name(对应的就是上面的name)
this.$router.push({ name: 'loginPage' }

带参数写法:

query方式:

this.$router.push({path:"/login",query:{message:"页面跳转成功"}})

 

注意:this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面及通过路由配置name属性访问

params方式:

this.$router.push({name:"loginPage",params:{message:"页面跳转成功"}})

 

//跳转到新页面/路由中 获取参数

this.$route.params // 获取一个对象

this.$route.params.message // 获取对象中具体得值

 

获取不到$router.push 参数问题:

注意this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面及通过路由配置name属性访问

 

两种方式的区别是:

  • query传参的参数会带在url后边展示在地址栏,
  •  

  • params传参的参数不会展示到地址栏(刷新后参数失效)。