axios 拦截器与 vuejs 自定义组件集成,以通用方式显示错误消息

tzo*_*zik 1 vue.js vue-component axios vuejs2

假设我们有以下代码

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  if (error.response.status === 400) {
    if (error.response.data.type === "fieldsValidationErrors") {
      openModal(modal.validationsFailedInfo);
    } else {
      openModal(modal.cannotHandleServerResponse);
    }
  } else if(error.response.status === 403) {
    redirectToLoginScreen();
  } else {
    openModal(modal.errorOccurred);
  }
  return Promise.reject(error);
});
Run Code Online (Sandbox Code Playgroud)

此代码包含在之前

const app1 = new Vue({...});
app1.init();
Run Code Online (Sandbox Code Playgroud)

我还有另一个 UI 应用程序:

const app2 = new Vue({...});
app2.init();
Run Code Online (Sandbox Code Playgroud)

axios 拦截器在声明 vue 实例之前声明。

在每个 vue 应用程序中,我都有一个<notifications type="danger" :messages="errors.items"></notifications>从应用程序接收错误的组件。

在notifications我拥有的组件内部

Vue.component('notifications', {
  ...
  template: '<section v-if="messages.length > 0" id="notifications" class="notifications-outer-wrapper">\n' +
    '    <div class="user-notification-content well form-group" :class="{ \'notify-danger\': type === \'danger\', \'notify-success\': type === \'success\' }">\n' +
    '      <span class="fa fa-info-circle notificationIcon" aria-hidden="true"></span>\n' +
    '      &nbsp;\n' +
    '      <span v-if="type === \'danger\'">{{message}}</span>\n' +
    '    </div>\n' +
    '  </section>'
});
Run Code Online (Sandbox Code Playgroud)

目前我正在使用模态来显示出现问题。我需要的是在<notifications>组件内显示错误消息,每个 Vue 实例都有一个通知组件。

关于如何获得这种行为的任何想法?

Jac*_*Goh 6

您可以使用全局事件总线在不同的实例之间进行通信。

// create a new Event Bus Instance
$eventBus = new Vue();

// set $eventBus as global Vue variable
// has to be done before new Vue({el: ...})
// after this, $eventBus instance can be acessed using this.$eventBus in all Vue components
Vue.prototype.$eventBus = $eventBus;

axios.interceptors.response.use(function(response) {
    return response;
}, function(error) {
    // ...

    // on error, emit an open modal event, add pass message as payload
    $eventBus.emit('open-modal', {
        type: 'error',
        message: '...'
    });
});

Vue.component('notifications', {
    created() {
        // listen to open-modal event
        this.$eventHub.$on('open-modal', ({
            type,
            message
        }) => {
            // logic for opening modal, etc...
        });
    },
    beforeDestroy() {
        this.$eventHub.$off('open-modal');
    },
});

const app1 = new Vue({ /* ... */ });
const app2 = new Vue({ /* ... */ });
Run Code Online (Sandbox Code Playgroud)