当前位置:首页 > VUE

vue 实现接口调用

2026-02-17 19:13:23VUE

使用 Axios 进行接口调用

安装 Axios 依赖:

npm install axios

在 Vue 组件中引入 Axios:

import axios from 'axios';

发送 GET 请求示例:

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

发送 POST 请求示例:

axios.post('https://api.example.com/data', { key: 'value' })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

配置全局 Axios 实例

创建全局配置:

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

设置请求拦截器:

vue 实现接口调用

instance.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer token';
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

设置响应拦截器:

instance.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    return Promise.reject(error);
  }
);

使用 async/await 语法

在 methods 中使用 async/await:

methods: {
  async fetchData() {
    try {
      const response = await axios.get('https://api.example.com/data');
      console.log(response.data);
    } catch (error) {
      console.error(error);
    }
  }
}

处理跨域问题

配置 vue.config.js 开发环境代理:

vue 实现接口调用

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
};

封装 API 模块

创建 api.js 文件:

import axios from 'axios';

const api = {
  getUser(id) {
    return axios.get(`/users/${id}`);
  },
  createUser(data) {
    return axios.post('/users', data);
  }
};

export default api;

在组件中使用:

import api from './api';

export default {
  methods: {
    async loadUser() {
      const user = await api.getUser(1);
      console.log(user);
    }
  }
}

处理加载状态

在组件中添加 loading 状态:

data() {
  return {
    isLoading: false,
    data: null
  };
},
methods: {
  async fetchData() {
    this.isLoading = true;
    try {
      const response = await axios.get('/api/data');
      this.data = response.data;
    } finally {
      this.isLoading = false;
    }
  }
}

错误处理最佳实践

统一错误处理方式:

async fetchData() {
  try {
    const response = await axios.get('/api/data');
    return response.data;
  } catch (error) {
    if (error.response) {
      // 服务器返回错误状态码
      console.log(error.response.status);
    } else if (error.request) {
      // 请求已发出但无响应
      console.log('No response received');
    } else {
      // 其他错误
      console.log('Error', error.message);
    }
    throw error;
  }
}

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

相关文章

vue实现visual

vue实现visual

Vue 实现可视化(Visual)的常见方法 在 Vue 中实现可视化通常涉及数据可视化库的集成,以下是几种主流方案: 使用 ECharts ECharts 是一个强大的 JavaScript 图表…

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转效…

vue element实现

vue element实现

Vue Element UI 实现 Vue Element UI 是基于 Vue.js 的组件库,提供丰富的 UI 组件,适合快速开发企业级中后台产品。以下是一些关键实现方法和步骤: 安装 Vue…

vue实现骰子

vue实现骰子

Vue 实现骰子功能 创建 Vue 组件 在 Vue 项目中创建一个骰子组件,例如 Dice.vue。该组件包含骰子的外观和逻辑。 <template> <div class=…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…