【发布时间】:2018-10-10 04:07:46
【问题描述】:
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component vue-router
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component vue-router
您可以使用 组件内防护 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);
});
}
如果应该继续,请使用next()。
如果要取消重定向,请使用next(false)。
【讨论】:
接受的答案显示了如何使用vuejs-dialog 来做到这一点。但是,如果您不想使用此库,请检查以下内容:
假设您有一个包含 3 个选项的对话框:
关闭对话框 => 调用closeDialog() 并停留在同一页面
保存更改 =>调用saveChanges()保存更改并离开
放弃更改 => 调用 discardChanges()navigates 离开而不保存更改
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);
}
}
See it in action in codesandbox
要点这里的关键要点是beforeRouteLeave 导航守卫,如果数据中的to 属性为空,我们不允许用户导航离开。唯一不能为 null 的情况是用户单击对话框中的保存或丢弃按钮。
【讨论】:
VueJS 有 In Component Navigation Guards,例如 beforeRouteUpdate 和 beforeRouteLeave
beforeRouteEnter (to, from, next) {
// called before the route that renders this component is confirmed.
// does NOT have access to `this` component instance,
// because it has not been created yet when this guard is called!
},
...
beforeRouteLeave (to, from, next) {
// called when the route that renders this component is about to
// be navigated away from.
// has access to `this` component instance.
}
【讨论】:
以下代码对我有用
<v-btn @click="deleteDialog = true">Delete</v-btn>
<v-dialog v-model="deleteDialog" max-width="500px">
<v-card>
<v-card-title style="font-size:20px" >Are you sure you want to archive?</v-card-title>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="red" style="font-size:15px" flat @click.native="deleteDialog = false">No</v-btn>
<v-btn color="green" style="font-size:15px" flat @click.native="deleteItem">Yes</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
【讨论】: