gpt4 book ai didi

vue.js - 在初始路由之前执行 Vuex 操作

转载 作者:行者123 更新时间:2023-12-02 19:01:37 24 4
gpt4 key购买 nike

我已经设置了 Vuex 和 Vue Router。我想显示一个设置页面,以防用户帐户未正确设置。这是通过对后端进行 API 调用来实现的。结果存储在 Vuex 内部并使用 getter 进行访问。该操作在根 Vuex 实例的 beforeCreate 中分派(dispatch):

new Vue({
router,
store,
render: h => h(App),

beforeCreate() {
this.$store.dispatch("config/get");
}
}).$mount("#app");

但是,我的路由器 beforeEach 从未收到 true 但 getter 肯定会根据 DevTools 返回 true:

router.beforeEach((to, next) => {
if (!to.matched.some(record => record.meta.requiresSetup)) {
next();
return;
}

if (!store.getters["config/isConfigured"]) { // Executed every time.
next("/setup");
return;
}

next();
});

最佳答案

延迟应用加载

即使钩子(Hook)被标记为async并且对某些异步操作执行await,也不可能使用生命周期钩子(Hook)来延迟加载。 Hook 并不是为了允许操作,只是为了提供对阶段的访问。

不过,您可以通过在商店操作完成之前不加载应用程序来延迟应用程序,但要意识到这对用户来说意味着一个空白页面,这是一种糟糕的用户体验。但您可以这样做:

ma​​in.js

const preload = async () => {
await store.dispatch('config/get'); // `await` store action which returns a promise

new Vue({
store,
router,
render: (h) => h(App)
}).$mount("#app");
}

preload();
console.log('LOADING...');

更好的方法

最好分派(dispatch)该操作,并且不要等待它。让App.vue加载并使用v-if显示启动屏幕,直到某些存储状态isLoadingfalse :

ma​​in.js

store.dispatch('config/get');

new Vue({
store,
router,
render: (h) => h(App)
}).$mount("#app");

App.vue

<template>
<div>
<div v-if="isLoading">
LOADING... <!-- Attractive splash screen here -->
</div>
<div v-else>
<router-view></router-view> <!-- Don't show the router view until ready -->
</div>
</div>
</template>

完全删除导航防护,并在App.vue中,在isLoading上放置一个监视。一旦不再加载,根据帐户 getter 的状态进行重定向:

computed: {
...mapState(['isLoading'])
},
methods: {
redirect() {
const path = this.$route.path;
if (!this.$store.getters["config/isConfigured"]) {
path !== '/setup' && this.$router.push({ path: '/setup' });
} else {
path !== '/' && this.$router.push({ path: '/' });
}
}
},
watch: {
isLoading(val) {
if (val === false) {
this.redirect();
}
}
}

关于vue.js - 在初始路由之前执行 Vuex 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65487609/

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