How to load all server side data on initial vue.js / vue-router load?

后端 未结 5 496
长发绾君心
长发绾君心 2020-11-29 22:42

I\'m currently making use of the WordPress REST API, and vue-router to transition between pages on a small single page site. However, when I make an AJAX call to the server

5条回答
  •  抹茶落季
    2020-11-29 23:00

    You can use navigation guards.

    On a specific component, it would look like this:

    export default {
        beforeRouteEnter (to, from, next) {
            // my ajax call
        }
    };
    

    You can also add a navigation guard to all components:

    router.beforeEach((to, from, next) => {
        // my ajax call
    });
    

    One thing to remember is that navigation guards are async, so you need to call the next() callback when the data loading is finished. A real example from my app (where the guard function resides in a separate file):

    export default function(to, from, next) {
        Promise.all([
            IngredientTypes.init(),
            Units.init(),
            MashTypes.init()
        ]).then(() => {
            next();
        });
    };
    

    In your case, you'd need to call next() in the success callback, of course.

提交回复
热议问题