You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目中封装Axios API 简化重复请求代码的可行方案

Simplifying Repeated Axios Requests in Vue

Absolutely, you can drastically reduce code duplication by creating a reusable API wrapper that handles common Axios logic, success/error notifications, and returns a consistent response object. Here's a step-by-step solution tailored to your needs:

Step 1: Create a Reusable API Mixin

Mixins are ideal here because they inject shared methods into your Vue components, giving direct access to component utilities like showSuccessMsg, showErrorMsg, and global app properties.

Create a file named apiMixin.js:

import axios from 'axios';

export const ApiMixin = {
  methods: {
    // Generic request method
    async $api(method, url, data = {}, options = {}) {
      try {
        // Build full URL using your app's base API URL
        const fullUrl = `${this.$root.api_url}${url}`;
        
        // Execute the Axios request
        const response = await axios({
          method,
          url: fullUrl,
          data,
        });

        // Customize success message (use provided option or default)
        const successMessage = options.successMessage || 
          (response.status === 201 ? 'Operation completed successfully!' : 'Request succeeded!');

        // Show success notification
        this.showSuccessMsg({
          title: options.successTitle || 'Success',
          message: successMessage,
        });

        // Fire custom event if specified
        if (options.eventName) {
          this.$events.fire(options.eventName, options.eventData || {});
        }

        // Return consistent success response
        return {
          message: successMessage,
          statusCode: response.status,
          data: response.data,
        };
      } catch (error) {
        // Customize error message (prioritize API errors, then Axios error, then default)
        const errorMessage = options.errorMessage || 
          error.response?.data?.message || 
          error.message || 
          'Something went wrong!';

        // Show error notification
        this.showErrorMsg({
          title: options.errorTitle || 'Error',
          message: errorMessage,
        });

        // Return consistent error response
        return {
          message: errorMessage,
          statusCode: error.response?.status || 500,
          error: error,
        };
      }
    },

    // Shortcut methods for common HTTP verbs (improves readability)
    async $apiGet(url, params = {}, options = {}) {
      return this.$api('get', url, params, options);
    },

    async $apiPost(url, data = {}, options = {}) {
      return this.$api('post', url, data, options);
    },

    async $apiPut(url, data = {}, options = {}) {
      return this.$api('put', url, data, options);
    },

    async $apiDelete(url, data = {}, options = {}) {
      return this.$api('delete', url, data, options);
    },
  },
};

Step 2: Register the Mixin

You can register the mixin globally (for all components) or locally in specific components:

Global Registration (main.js)

import Vue from 'vue';
import { ApiMixin } from './path/to/apiMixin';

Vue.mixin(ApiMixin);

Local Registration (in a component)

import { ApiMixin } from './path/to/apiMixin';

export default {
  mixins: [ApiMixin],
  // ... rest of component code
};

Step 3: Simplify Your Component Code

Replace your long Axios request with the streamlined mixin method. Using your snapshot extractor example:

async handleSnapshotExtract() {
  // Prepare your request data
  const requestData = {
    start_date: moment(this.fromDateTime).format(),
    end_date: moment(this.toDateTime).format(),
    schedule: this.schedule,
    interval: this.interval,
    create_mp4: this.create_mp4,
    inject_to_cr: this.inject_to_cr,
    jpegs_to_dropbox: this.jpegs_to_dropbox,
    requester: this.$root.user.email,
    api_key: this.selected.api_key,
    api_id: this.selected.api_id,
  };

  // Execute the request with custom options
  const result = await this.$apiPost(
    `/v2/cameras/${this.selected.exid}/nvr/snapshots/extract`,
    requestData,
    {
      successMessage: 'Snapshot Extractor has been added (Local)!',
      eventName: 'se-added',
    }
  );

  // Perform post-success actions (like clearing the form)
  if (result.statusCode === 201) {
    this.clearForm();
  }
}

Key Benefits

  1. Reduced Duplication: No more copying Axios configs and response logic across 13 requests.
  2. Consistent Handling: Success/error notifications and response formats are standardized everywhere.
  3. Easy Maintenance: Update notification logic or Axios settings in one place.
  4. Readable Code: Component code focuses on business logic rather than HTTP boilerplate.

Customization Options

  • Add more shortcut methods (like $apiPatch) if needed.
  • Extend the options parameter to include headers, timeouts, or other Axios settings.
  • Add Axios interceptors for global transformations (e.g., attaching auth tokens).

内容的提问来源于stack exchange,提问作者Junaid Farooq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:25