vue-router传递参数的几种方式
一、编程式的导航 router.push
编程式导航传递参数有两种类型:字符串、对象。
字符串
字符串的方式是直接将路由地址以字符串的方式来跳转,不能传递参数:
this.$router.push("home");
对象
两种方式:命名路由、查询参数,
注意:和name配对的是params,和path配对的是query
// 1.查询参数 url传递 ( /home?id=123 ) 刷新页面数据不会丢失
this.$router.push({path: '/home', query: {id: 123}});
// 获取参数
this.$route.query.id;
// 2.命名路由 参数不在链接上显示 ( /home ) 刷新页面参数会丢失
this.$router.push({ name: 'home', params: { userId: 123 }});
// 获取参数
{{this.$route.params.userId}};
// 注:采用params在必须要要在路由上配置name,否则undefined
routes: [
{
path: '/home',
name: 'home',
component: resolve => require(['../components/home'], resolve)
}
]
二、声明式的导航
字符串
<router-link to=“page”>跳转新页面</router-link>
命名路由
<router-link :to="{ name: ‘page’, params: { userId: 111}}">跳转新页面</router-link>
查询参数
<router-link :to="{ path: ‘/page’, query: { userId: 111}}">跳转新页面</router-link>
补充
点击父组件 按钮 跳转携带参数,便于子组件获取数据,例
<button v-for="item in data" @click="getPage(item.id)">
getPage(id) {
// 直接调用$router.push 实现携带参数的跳转
this.$router.push({
path: `/page/${id}`,
})
需要对应路由配置(刷新页面id会保留)如下:
{
path: '/page/:id',
name: 'Page',
component: Page
}
/page/1 or /page/2 …