在我的一个观点(组件)中,我遇到了类似的问题。我试图(以编程方式)从/foo/bar 导航到/foo/bar/123,但后来组件中的路由参数不可用。我的相关导航代码如下所示:
methods: {
save_obj() {
let vm = this;
// Make AJAX call to save vm.my_obj, and on success do:
let v = `${vm.$route.path}/${vm.my_obj.id}`;
console.log("Loading view at path: "+v);
vm.$router.push({ path: v });
},
...
}
它将打印预期的日志(例如,在路径:/foo/bar/112 处加载视图),但是,created() 钩子中的数据加载将不会收到路由参数的值。我失败的created() 代码如下所示:
created: function() {
console.log("Loading object details.");
let vm = this;
let cid = vm.$route.params.id; // <---- This was the problem
vm.$http.get('api/'+cid)
.then(function (res) {
if (res.data.status == "OK") {
vm.my_obj = res.data.body;
} else {
vm.setStatusMessage(res.data.body);
}
})
.catch(function (error) {
console.log(error);
vm.setStatusMessage("Error: "+error);
});
}
下面引用的the third note here 中指出了解决方案:
注意:如果目的地与当前路线相同且仅
参数正在改变(例如,从一个配置文件转到另一个 /users/1
-> /users/2),您必须使用 beforeRouteUpdate 来响应更改(例如获取用户信息)。
我必须在我的组件中执行以下操作:
将created()中的let cid = vm.$route.params.id;行改为let cid = vm.course.id
并且,将以下内容添加到组件中:
beforeRouteUpdate(to, from, next) {
if (to.params.id) {
this.my_obj.id = to.params.id;
}
// Some other code specific to my app
next();
}
我希望这可以帮助遇到类似问题的人。