MST

星途 面试题库

面试题:Vue中如何优雅地实现带自动关闭功能的全局提示框配合网络请求

在Vue应用中,要求在每次网络请求成功或失败时,弹出一个全局提示框,成功提示框3秒后自动关闭,失败提示框需用户手动关闭。使用Vuex管理状态,结合自定义指令或插件机制来实现该功能,描述详细的实现步骤及关键代码逻辑。
46.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 创建Vuex模块
    • store目录下创建一个新的模块,例如notification.js
    const state = {
      message: '',
      type: '',
      visible: false
    };
    const mutations = {
      SET_NOTIFICATION(state, { message, type }) {
        state.message = message;
        state.type = type;
        state.visible = true;
      },
      CLOSE_NOTIFICATION(state) {
        state.message = '';
        state.type = '';
        state.visible = false;
      }
    };
    const actions = {
      showNotification({ commit }, { message, type }) {
        commit('SET_NOTIFICATION', { message, type });
        if (type ==='success') {
          setTimeout(() => {
            commit('CLOSE_NOTIFICATION');
          }, 3000);
        }
      }
    };
    export default {
      namespaced: true,
      state,
      mutations,
      actions
    };
    
  2. 注册Vuex模块
    • store/index.js中注册上述模块。
    import Vue from 'vue';
    import Vuex from 'vuex';
    import notification from './notification';
    Vue.use(Vuex);
    const store = new Vuex.Store({
      modules: {
        notification
      }
    });
    export default store;
    
  3. 创建全局提示框组件
    • components目录下创建Notification.vue
    <template>
      <div v-if="visible" :class="['notification', type]">
        {{ message }}
        <button v-if="type === 'error'" @click="closeNotification">关闭</button>
      </div>
    </template>
    <script>
    import { mapState, mapMutations } from 'vuex';
    export default {
      computed: {
       ...mapState('notification', ['message', 'type', 'visible'])
      },
      methods: {
       ...mapMutations('notification', ['CLOSE_NOTIFICATION']),
        closeNotification() {
          this.CLOSE_NOTIFICATION();
        }
      }
    };
    </script>
    <style scoped>
    

.notification { position: fixed; top: 20px; right: 20px; padding: 10px 20px; border - radius: 5px; color: white; } .success { background - color: green; } .error { background - color: red; }

4. **在App.vue中引入提示框组件**:
```html
<template>
  <div id="app">
    <Notification />
    <router - view />
  </div>
</template>
<script>
import Notification from './components/Notification.vue';
export default {
  components: {
    Notification
  }
};
</script>
  1. 使用自定义指令或插件机制
    • 自定义指令方式
      • directives目录下创建httpNotification.js
      import { mapActions } from 'vuex';
      export default {
        inserted(el, binding, vnode) {
          const { showNotification } = vnode.context.$store.dispatch;
          const originalFetch = window.fetch;
          window.fetch = async (...args) => {
            try {
              const response = await originalFetch(...args);
              showNotification({ message: '请求成功', type:'success' });
              return response;
            } catch (error) {
              showNotification({ message: '请求失败', type: 'error' });
              throw error;
            }
          };
        }
      };
      
      • main.js中注册自定义指令。
      import Vue from 'vue';
      import httpNotification from './directives/httpNotification';
      Vue.directive('http - notification', httpNotification);
      
      • 在需要的组件模板中使用指令,例如App.vue
      <template>
        <div id="app" v - http - notification>
          <Notification />
          <router - view />
        </div>
      </template>
      
    • 插件方式
      • 创建一个插件文件httpNotificationPlugin.js
      import { mapActions } from 'vuex';
      export default {
        install(Vue, options) {
          const { showNotification } = Vue.prototype.$store.dispatch;
          const originalFetch = window.fetch;
          window.fetch = async (...args) => {
            try {
              const response = await originalFetch(...args);
              showNotification({ message: '请求成功', type:'success' });
              return response;
            } catch (error) {
              showNotification({ message: '请求失败', type: 'error' });
              throw error;
            }
          };
        }
      };
      
      • main.js中注册插件。
      import Vue from 'vue';
      import httpNotificationPlugin from './httpNotificationPlugin';
      Vue.use(httpNotificationPlugin);
      

关键代码逻辑总结:

  • Vuex模块:用于管理提示框的状态,包括消息内容、类型和是否显示。actions中的showNotification方法根据不同类型控制提示框的显示和关闭。
  • 提示框组件:通过计算属性从Vuex中获取状态,根据不同类型显示不同样式的提示框,并提供关闭按钮用于手动关闭错误提示框。
  • 自定义指令或插件:通过重写window.fetch方法,在请求成功或失败时调用Vuex的showNotification方法,从而触发提示框的显示。