我希望在一个组件离开之前完成一些信息验证。
我已经扫描了vue-router
文档:https://router.vuejs.org
但我在我的文件中使用vue-cli
:router1.vue,
console.log(this.$router.beforeLeave) -> undefined
我该如何使用它?
答案 0 :(得分:2)
将此添加到您的router1.vue
:
export default {
//...
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.
},
//...
}
例如:
beforeRouteLeave (to, from , next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}
在这条路线离开之前它会被召唤。
参考:https://router.vuejs.org/en/advanced/navigation-guards.html