Sag*_*che 9 javascript vue.js vue-router vue-component vuejs2
在我的vueJS项目中,我想在当前路由更改之前显示确认对话框.

是的,它应该重定向到下一个期望的路线,否则保持在相同的路线上.
知道如何实现它吗?
提前致谢.
Jac*_*Goh 20
您可以使用组件内保护 beforeRouteLeave.请参阅https://router.vuejs.org/en/advanced/navigation-guards.html.
演示:https://codesandbox.io/s/jzr5nojn39(尝试在家中导航,第1页,第2页)
示例代码(使用vuejs-dialog作为确认对话框):
beforeRouteLeave (to, from, next) {
this.$dialog.confirm('Do you want to proceed?')
.then(function () {
next();
})
.catch(function () {
next(false);
});
}
Run Code Online (Sandbox Code Playgroud)
如果要继续,请使用next().
如果应取消重定向,请使用next(false).
rol*_*oli 10
接受的答案显示了如何使用vuejs-dialog做到这一点。但是,如果您不想使用此库,请检查以下内容:
假设您有一个包含 3 个选项的对话框:
关闭对话框=> 调用closeDialog()并停留在同一页面
保存更改=> 调用saveChanges()保存更改并导航离开
丢弃更改=> 调用discardChanges()导航离开而不保存更改
data: () => ({
to: null,
showDialog: false
}),
beforeRouteLeave(to, from, next) {
if (this.to) {
next();
} else {
this.to = to;
this.showDialog = true;
}
},
methods: {
closeDialog() {
this.showDialog = false;
this.to = null;
},
saveChanges() {
// add code to save changes here
this.showDialog = false;
this.$router.push(this.to);
},
discardChanges() {
this.showDialog = false;
this.$router.push(this.to);
}
}
Run Code Online (Sandbox Code Playgroud)
要点这里的关键要点是beforeRouteLeave导航守卫,如果todata 中的属性为空,我们不允许用户导航离开。它不能为空的唯一情况是当用户单击对话框中的保存或放弃按钮时。
| 归档时间: |
|
| 查看次数: |
4947 次 |
| 最近记录: |