使用beforeRouteEnter
导航守卫:在组件定义时,通过beforeRouteEnter
导航守卫来确保在路由进入组件之前执行相应的代码。例如
export default {
data() {},
beforeRouteEnter(to, from, next) {
next(vm => {
// 在组件实例化之前执行一些逻辑
vm.customLogic();
});
},
created() {
// 此时`created`钩子函数将会执行
},
mounted() {
// 此时`mounted`钩子函数将会执行
},
methods: {
customLogic() {
// 定义在`beforeRouteEnter`中调用的自定义逻辑
},
},
};
- 使用
beforeRouteUpdate
导航守卫:如果你已经进入了组件并且下一次访问同一个组件,可以使用beforeRouteUpdate
导航守卫来执行相应的代码,如下所示:export default { data() {}, beforeRouteUpdate(to, from, next) { // 执行一些逻辑 this.customLogic(); next(); }, created() { // 第一次进入页面时,`created`钩子函数将会执行 }, mounted() { // 第一次进入页面时,`mounted`钩子函数将会执行 }, methods: { customLogic() { // 定义在`beforeRouteUpdate`中调用的自定义逻辑 }, }, };
通过以上方法,可以确保在Vue路由中多次进入同一个页面时,
created
和mounted
钩子函数都能被正确执行。