天天看点

Vue 路由转跳及传递参数

使用params

使用这个,需要提前在路由中配置

url的表现形式

http://localhost:8080/#/detail/1
           

路由配置

{
    name:"detail",
  path:'/detail/:id',
  component: detail,
}
           

js实现

this.$router.push({
    name: 'detail', 
    params:{id: item.id}
   });
           

页面中传递参数

<router-link :to="{ name:'detail', params: {id: item.id} }"></button>显示<button></router-link>

<router-link :to="`/detail/${item.id}`"><button>显示</button></router-link>
           

获取参数

this.$route.params.id
           

使用query

使用这个,不需要在路由中配置

url的表现形式

http://localhost:8080/#/detail?id=1
           

路由配置

{
   path:'/detail',
   component: detail,
}
           

js实现

this.$router.push({
    path: '/detail', 
    query:{id: item.id}
   });
           

页面中传递参数

<router-link :to="{ path:'/detail', query: {id: item.id} }"><button>显示</button></router-link>

<router-link :to="`/detail?id=${item.id}`"><button>显示</button></router-link>
           

获取参数

this.$route.query.id
           

params与query对比

  • params传递参数,url相对较为隐蔽,没有完全暴露;query传递参数,可以直观的看到参数名、参数值;
  • params传递参数,一定需要传值,不传值,则无法进入页面;query不传值,也可进入到页面;
  • 使用params时,路由改变,只需要修改router,具体业务中不需要关注;使用query时,路由调整,则需要检查业务代码中的;