当前位置:首页 > VUE

vue 实现接口调用

2026-01-17 02:45:02VUE

使用 Axios 进行接口调用

安装 Axios 依赖:

npm install axios

在 Vue 组件中引入并使用:

import axios from 'axios';

export default {
  methods: {
    fetchData() {
      axios.get('https://api.example.com/data')
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
}

封装 API 请求模块

创建 api.js 文件统一管理接口:

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000
});

export const getData = () => api.get('/data');
export const postData = (payload) => api.post('/data', payload);

在组件中使用封装后的 API:

vue 实现接口调用

import { getData } from '@/api';

export default {
  methods: {
    async loadData() {
      try {
        const response = await getData();
        this.data = response.data;
      } catch (error) {
        console.error(error);
      }
    }
  }
}

使用 Vuex 管理接口状态

在 store 中定义接口相关状态:

import { getData } from '@/api';

export default {
  state: {
    data: null,
    loading: false,
    error: null
  },
  mutations: {
    setData(state, payload) {
      state.data = payload;
    },
    setLoading(state, payload) {
      state.loading = payload;
    },
    setError(state, payload) {
      state.error = payload;
    }
  },
  actions: {
    async fetchData({ commit }) {
      commit('setLoading', true);
      try {
        const response = await getData();
        commit('setData', response.data);
      } catch (error) {
        commit('setError', error.message);
      } finally {
        commit('setLoading', false);
      }
    }
  }
}

处理请求拦截和响应拦截

在 Axios 实例中添加拦截器:

vue 实现接口调用

api.interceptors.request.use(config => {
  // 添加请求头等预处理
  config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
  return config;
}, error => {
  return Promise.reject(error);
});

api.interceptors.response.use(response => {
  // 响应数据预处理
  return response.data;
}, error => {
  // 统一错误处理
  if (error.response.status === 401) {
    router.push('/login');
  }
  return Promise.reject(error);
});

使用 async/await 语法

推荐使用 async/await 处理异步请求:

export default {
  methods: {
    async submitForm() {
      try {
        const response = await api.post('/submit', this.formData);
        this.$message.success('提交成功');
      } catch (error) {
        this.$message.error(error.message);
      }
    }
  }
}

处理跨域问题

在开发环境中配置代理:

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://api.example.com',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

取消重复请求

使用 Axios 的 CancelToken 防止重复请求:

const pendingRequests = new Map();

function addPendingRequest(config) {
  const requestKey = `${config.method}-${config.url}`;
  config.cancelToken = new axios.CancelToken(cancel => {
    if (!pendingRequests.has(requestKey)) {
      pendingRequests.set(requestKey, cancel);
    }
  });
}

function removePendingRequest(config) {
  const requestKey = `${config.method}-${config.url}`;
  if (pendingRequests.has(requestKey)) {
    const cancel = pendingRequests.get(requestKey);
    cancel();
    pendingRequests.delete(requestKey);
  }
}

api.interceptors.request.use(config => {
  removePendingRequest(config);
  addPendingRequest(config);
  return config;
});

api.interceptors.response.use(response => {
  removePendingRequest(response.config);
  return response;
});

标签: 接口vue
分享给朋友:

相关文章

vue实现选择本地文件

vue实现选择本地文件

实现文件选择功能 在Vue中实现本地文件选择可以通过HTML原生的<input type="file">元素实现。创建一个基本的文件选择组件: <template> &l…

vue实现矩阵

vue实现矩阵

Vue 实现矩阵的方法 在 Vue 中实现矩阵操作可以通过多种方式完成,以下是一些常见的方法: 使用二维数组表示矩阵 矩阵可以用二维数组来表示,每个元素对应矩阵中的一个值。在 Vue 的 data…

vue实现盖章

vue实现盖章

Vue 实现盖章功能 在Vue中实现盖章功能通常涉及前端UI交互,通过Canvas或SVG绘制印章,并允许用户拖拽或点击放置印章。以下是具体实现方法: 使用Canvas绘制印章 通过HTML5的Ca…

vue实现token

vue实现token

Vue 中实现 Token 认证的方法 在 Vue 中实现 Token 认证通常涉及前端与后端的交互,包括 Token 的获取、存储、发送和刷新等操作。以下是具体实现步骤: 获取 Token 用户登…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue实现布局

vue实现布局

Vue 实现布局方法 Vue 提供了多种方式实现页面布局,可以通过组件化、CSS 框架或自定义样式完成。以下是几种常见方法: 使用 CSS Flexbox 或 Grid 通过 Vue 单文件组件结合…