Vue Router - доступ к экземпляру Vue без вызова next () - PullRequest
0 голосов
/ 18 марта 2020

Я взламываю на способ доставки sh моего SPA на маршрут, если, например, проверка не пройдена. Я использую методы beforeRouteEnter и beforeRouteUpdate для запуска функции, чтобы определить это;

...
beforeRouteEnter(to, from, next) {
    loading(next);
},
beforeRouteUpdate(to, from, next) {
    loading(next);
},
...

И затем эту функцию для проверки (это просто временно, пока я не выясню это).

let loading = function(callback) {
    db.commit('setPageLoading', true);
    new requests().concat([
        'UserController@userDetails',
        'SettingController@settings',
        'ClientController@allClients',
        'StatsController@statsUsage',
        'UserController@paymentDetails'],
    () => {
        db.commit('setPageLoading', false);
        /** everything's all gravy, `next()` should be called now! */
        callback();
    },
    (error) => {
        /**
        * I dont want to call `next()` to access the vue instance as it will show the requested page
        * but I have to to access the router!!!
        **/
        callback(vm => {
            switch(error.response.status) {
                case 401:
                    /** Put login box here, this will do for now **/
                    vm.$router.push('/login').catch(err => {});
                break;
                /** Custom error to tell the SPA the user needs to fill in their company details first */
                case 498:
                    for(let i in error.response.data.errors) {
                        db.commit('addErrorNotification', error.response.data.errors[i][0]);
                    }
                    vm.$router.push('/profile').catch(err => {});
                break;
            }
        });
    });
};

Моя проблема в том, что мне нужно позвонить next(), чтобы получить доступ к экземпляру vue, чтобы pu sh по другому маршруту. Но мой вызов обратного вызова next(), он говорит Vue Маршрутизатор продолжать загрузку текущего или ожидающего маршрута, а это не то, чего я хочу.

Может кто-нибудь сказать мне, как я могу получить доступ к Vue экземпляр без вызова next() обратного вызова?

С уважением

1 Ответ

0 голосов
/ 18 марта 2020

Как описано Delena Malan, спасибо!;

let loading = function(callback) {
    db.commit('setPageLoading', true);
    new requests().concat([
        'UserController@userDetails',
        'SettingController@settings',
        'ClientController@allClients',
        'StatsController@statsUsage',
        'UserController@paymentDetails'],
    () => {
        db.commit('setPageLoading', false);
        /** everything's all gravy, `next()` should be called now! */
        callback();
    },
    (error) => {
        switch(error.response.status) {
            case 401:
                /** Put login box here, this will do for now **/
                callback({ path: '/login' });
            break;
            case 498:
                for(let i in error.response.data.errors) {
                    db.commit('setNotifications', []);
                    db.commit('addErrorNotification', error.response.data.errors[i][0]);
                }
                callback({ path: '/profile' });
            break;
        }
        db.commit('setPageLoading', false);
    });
};
...