如何获取router.back传递的参数
要获取 router.back
传递的参数,你需要在执行 router.back
之前将这些参数添加到 history 对象中。这可以通过 history.push
或 history.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
}
解决措施
在onPageShow回调方法里通过router.getParams方法获取返回值。
示例代码
参考链接
页面跳转