当前位置:首页 > 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 中实现静态查询通常指不依赖后端接口,直接在前端处理数据筛选或搜索功能。以下是几种常见实现方式: 使用计算属性过滤数据 通过计算属性对静态数据进行筛选,适合简单查询…

vue实现点击页面切换

vue实现点击页面切换

实现点击页面切换功能 在Vue中实现点击页面切换功能,可以通过路由跳转或组件动态渲染两种方式完成。以下是具体实现方法: 使用Vue Router实现页面跳转 安装Vue Router后,在项目中…

vue实现走势图

vue实现走势图

Vue 实现走势图的方法 使用 ECharts 库 ECharts 是一个强大的数据可视化库,支持多种图表类型,包括走势图(折线图)。在 Vue 项目中可以通过 vue-echarts 封装库或直接使…

vue中实现显示和隐藏

vue中实现显示和隐藏

控制显示与隐藏的方法 在Vue中实现元素的显示和隐藏可以通过多种方式完成,以下是常见的几种方法: 1. 使用v-if指令v-if根据条件动态添加或移除DOM元素,适合需要频繁切换的场景。当条件为f…

vue中登陆实现逻辑

vue中登陆实现逻辑

Vue 中登录实现逻辑 前端实现逻辑 表单验证 使用 Vue 的表单验证库(如 VeeValidate)或自定义验证规则,确保用户输入的账号和密码符合要求。例如,检查邮箱格式、密码长度等。 发送登录…

用vue实现滑动输入条

用vue实现滑动输入条

使用 Vue 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…