欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Vue Router: 传递参数的两大方法详解 - 方案二:通过params传递显式参数

最编程 2024-08-01 19:50:50
...

params 传参(显示参数)又可分为 声明式编程式 两种方式

1、声明式 router-link

该方式是通过 router-link 组件的 to 属性实现,该方法的参数可以是一个字符串路径,或者一个描述地址的对象。使用该方式传值的时候,需要子路由提前配置好参数,例如:

//子路由配置
{
  path: '/child/:id',
  component: Child
}
//父路由组件
<router-link :to="/child/123">进入Child路由</router-link>

2、编程式 this.$router.push

使用该方式传值的时候,同样需要子路由提前配置好参数,例如:

//子路由配置
{
  path: '/child/:id',
  component: Child
}
//父路由编程式传参(一般通过事件触发)
this.$router.push({
    path:`/child/${id}`, // 模板字符串形式
})

接收参数:在子路由中可以通过下面代码来获取传递的参数值

this.$route.params.id
console.log( this.$route.params ) // { id:123 }
console.log( this.$route.params.id ) // 123

推荐阅读