Vue项目中封装Axios API 简化重复请求代码的可行方案
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
- Reduced Duplication: No more copying Axios configs and response logic across 13 requests.
- Consistent Handling: Success/error notifications and response formats are standardized everywhere.
- Easy Maintenance: Update notification logic or Axios settings in one place.
- Readable Code: Component code focuses on business logic rather than HTTP boilerplate.
Customization Options
- Add more shortcut methods (like
$apiPatch) if needed. - Extend the
optionsparameter to include headers, timeouts, or other Axios settings. - Add Axios interceptors for global transformations (e.g., attaching auth tokens).
内容的提问来源于stack exchange,提问作者Junaid Farooq

