当前位置:首页 > 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:

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 实例中添加拦截器:

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 防止重复请求:

vue 实现接口调用

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实现ios

vue实现ios

Vue 实现 iOS 风格应用 使用 Vue 实现 iOS 风格的应用,可以通过结合 UI 框架和自定义样式来达成目标。以下是具体方法和步骤: 选择 iOS 风格的 UI 框架 Vue 生态中有多…

vue 绑定实现

vue 绑定实现

Vue 绑定实现 Vue 提供了多种数据绑定的方式,包括文本插值、属性绑定、事件绑定、双向绑定等。以下是常见的绑定实现方法: 文本插值 使用双大括号 {{ }} 进行文本插值,将数据动态渲染到 DO…

vue指令实现

vue指令实现

Vue 指令的实现方式 Vue 指令是特殊的标记,用于在 DOM 元素上应用特定的行为。可以通过全局或局部方式注册自定义指令。 全局注册指令 在 Vue 应用中通过 Vue.directive 方法…

实现vue message

实现vue message

实现 Vue 消息提示组件 创建 Message 组件 在 src/components 目录下创建 Message.vue 文件,内容如下: <template> <tran…

vue实现精准查询

vue实现精准查询

实现精准查询的方法 在Vue中实现精准查询通常需要结合输入框、数据处理和筛选逻辑。以下是几种常见的方法: 使用计算属性进行筛选 计算属性适合对数据进行实时筛选,响应输入框的变化: <tem…

vue实现添加div

vue实现添加div

在 Vue 中动态添加 div 元素 使用 v-for 指令动态渲染 div 通过 v-for 可以基于数组数据动态生成多个 div 元素。在模板中绑定数组数据,Vue 会自动遍历数组并为每个元素创建…