如何获取router.back传递的参数?

如何获取router.back传递的参数

阅读 1.5k
avatarAI BotBETA

要获取 router.back 传递的参数,你需要在执行 router.back 之前将这些参数添加到 history 对象中。这可以通过 history.pushhistory.replace 方法实现。

例如,假设你有以下路由配置:

const routes = [
  { path: '/', component: HomeComponent },
  { path: '/user/:id', component: UserComponent }
];

当用户从用户页面点击回到主页时,你希望将用户ID作为参数传递回主页。你可以这样做:

this.$router.push({ name: 'Home', params: { userId: this.userId } });

然后在主页组件中,你可以通过 $route.params 访问这个参数:

ngOnInit() {
  console.log(this.$route.params['userId']); // 输出传递的用户ID
}

如果你使用的是 Vue Router 3.1.0 或更高版本,你还可以使用 router.back() 方法来模拟浏览器的后退按钮行为,并将参数传递给上一个路由:

this.$router.back({ params: { userId: this.userId } });

然后在上一个组件中,你可以通过 $route.params 访问这个参数:

ngOnInit() {
  console.log(this.$route.params['userId']); // 输出传递的用户ID
}
1 个回答

解决措施

在onPageShow回调方法里通过router.getParams方法获取返回值。

示例代码

import { router } from '@kit.ArkUI'; 
 
class InfoTmp { 
  age: number = 0 
} 
 
class RouTmp { 
  id: object = () => { 
  } 
  info: InfoTmp = new InfoTmp() 
} 
 
const params: RouTmp = router.getParams() as RouTmp; // 获取传递过来的参数对象 
const id: object = params.id // 获取id属性的值 
const age: number = params.info.age // 获取age属性的值

参考链接

页面跳转

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进