为什么使用 beforeRouteEnter 而不是 mounted?
Why use beforeRouteEnter instead of mounted?
为什么vue-router中存在beforeRouteEnter
导航守卫?是否存在 beforeRouteEnter
会被解雇但 mounted
不会被解雇的情况?如果不是,在什么情况下您更喜欢使用 beforeRouteEnter
而不是 mounted
?
mounted
是任何 Vue 组件的生命周期钩子,它总是会被触发。 beforeRouteEnter
或 vue-router
添加的任何其他生命周期挂钩的想法是允许您控制您的应用程序。
例如,假设您有一个名为 bar
的路由,它具有非常具体的验证逻辑,仅当前一个路由为 foo
时才允许用户输入,您可以在此挂钩中插入验证逻辑,而不是检查全局守卫中的每个路由更改。
export default {
name: 'Bar',
beforeRouteEnter(to, from, next) {
if (from.name === 'foo') {
next(); // Calling next allow the route to proceed
} else {
next(false); // Don't allow the navigation
// or
next({
name: 'foo',
query: {
from: 'bar'
}
}); // Redirect to any desired route as navigation made in $router
}
}
}
为什么vue-router中存在beforeRouteEnter
导航守卫?是否存在 beforeRouteEnter
会被解雇但 mounted
不会被解雇的情况?如果不是,在什么情况下您更喜欢使用 beforeRouteEnter
而不是 mounted
?
mounted
是任何 Vue 组件的生命周期钩子,它总是会被触发。 beforeRouteEnter
或 vue-router
添加的任何其他生命周期挂钩的想法是允许您控制您的应用程序。
例如,假设您有一个名为 bar
的路由,它具有非常具体的验证逻辑,仅当前一个路由为 foo
时才允许用户输入,您可以在此挂钩中插入验证逻辑,而不是检查全局守卫中的每个路由更改。
export default {
name: 'Bar',
beforeRouteEnter(to, from, next) {
if (from.name === 'foo') {
next(); // Calling next allow the route to proceed
} else {
next(false); // Don't allow the navigation
// or
next({
name: 'foo',
query: {
from: 'bar'
}
}); // Redirect to any desired route as navigation made in $router
}
}
}