Vue路由器-访问Vue实例而无需调用next()

时间:2020-03-18 11:27:59

标签: vue.js vue-router

例如,如果验证失败,我正在设法将SPA推到某个路由。我正在使用beforeRouteEnterbeforeRouteUpdate方法来运行函数来确定这一点;

...
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实例以推送到其他路由。但是我调用了next()回调,它告诉Vue Router继续加载当前或未完成的路由,这不是我想要的。

有人能告诉我一种无需调用next()回调即可访问Vue实例的方法吗?

致谢

1 个答案:

答案 0 :(得分:0)

如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);
    });
};