gpt4 book ai didi

vue.js - 在 beforeRouteEnter 中访问应用程序

转载 作者:搜寻专家 更新时间:2023-10-30 22:47:47 30 4
gpt4 key购买 nike

我想在组件准备由 vue 路由器渲染时在应用程序根目录中显示一些加载动画。

已找到this question ,建议使用导航守卫,以及another question ,其中接受的答案显示如何使用 beforeEach 守卫在 app 中设置变量,显示加载动画。

问题是这在深层链接到某些路由时不起作用(初始 url 包含路由路径,例如“someurl#/foo”)。 beforeEach 守卫根本不会被调用。

所以我切换到加载组件的 beforeRouteEnter 守卫,这也允许我仅显示某些组件的加载动画:

应用:

var app = new Vue({
el: '#app',
data: { loading: false }
router: router
});

组件:

var Foo = { 
template: '<div>bar</div>',
beforeRouteEnter: function(to, from, next) {
app.loading = true; // 'app' unavailable when deep-linking
// do some loading here before calling next()...
next();
}
}

但后来我发现当深度链接到组件时,appbeforeRouteEnter 中不可用,因为它在初始化过程的早期被调用。

我不想在应用程序数据声明中将 loading 设置为 true,因为我可能会在某个时候决定深度链接到另一个路由,其组件不需要加载动画。

最佳答案

我相信,您的解决方案是正确的。但是,我建议改用 next() 函数。如 vue-router 文档中所写。 https://router.vuejs.org/en/advanced/navigation-guards.html

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:

beforeRouteEnter (to, from, next) {
next(vm => {
vm.$root.loading = true;
})
}

关于vue.js - 在 beforeRouteEnter 中访问应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49276470/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com