当前位置:首页 > 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 实现用户注册功能 环境准备 确保已安装 Vue CLI 或通过 CDN 引入 Vue。若使用 Vue CLI,需安装 axios 或其他 HTTP 库用于后端通信。 注册表单组件 创…

vue 页签实现

vue 页签实现

Vue 页签实现方法 在 Vue 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-…

前端vue登录功能实现

前端vue登录功能实现

Vue 登录功能实现步骤 创建登录表单组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含用户名和密码输入框以及提交按钮。 <template> &l…

vue实现冰墩墩

vue实现冰墩墩

使用 Vue 实现冰墩墩动画 通过 Vue 的动画特性和 SVG 技术,可以动态渲染冰墩墩的形象。以下是具体实现方法: 准备 SVG 素材 冰墩墩的形象通常由多个 SVG 路径组成,包括身体轮廓、面…

vue实现双折线图

vue实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 EC…

vue实现钟表

vue实现钟表

使用 Vue 实现动态钟表 以下是一个基于 Vue 3 的动态钟表实现方案,包含时分秒指针和数字时间显示。 模板部分 <template> <div class="clock-…