Vuejs router beforeEach:如果state为true,则运行代码,否则将异步数据加载到状态,然后运行相同的代码

时间:2017-09-12 19:42:24

标签: javascript vue.js vue-router vuex

我在SPA中使用了VueJS,VueRouter和VueX 我希望我的应用程序在启动时加载一些数据,在多个路由下需要。该数据存储在VueX的状态中 以下是我使用路由器所做的事情,并在评论中做了解释,希望它足够清晰:

router.beforeEach((to, from, next) => {
if (!store.getters.getStartUp()) { // a getter function returning boolean value of a state flag property named startUp, false by default and set to true when I have loaded the required data (in the created method of the main Vue instance (see next code example)

    const watcher = store.watch(store.getters.getStartUp, () => {
        watcher(); // cancel the watcher

        // Here is the code block I need to reuse
        if (to.matched.some(record => record.meta.forVisitors)) {
            if (Vue.auth.isLoggedIn()) {
                next({
                    path: '/'
                });
            }
        } else if (to.matched.some(record => record.meta.forAuth)) {
            if (!Vue.auth.isLoggedIn()) {
                next({
                    path: '/login'
                });
            }
        }

        next();
        // end of code block

    });
} else {
    // execute the same code block which is ran in the watcher.
    // what is the best pattern to do that ? 
    // a simple function defined in the beforeEach ? using Promises ?
}
});

以下是我在主Vue实例的创建方法中添加的内容:

created() {
    if (!store.state.startUp) {
        Promise.all([
            store.dispatch('getSomeData1'),
            store.dispatch('getSomeData2'),
        ])
            .then(() => {
                store.commit('setStartUp'); // set the state flag property to true
            });
    }
}

谢谢!

0 个答案:

没有答案