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

设置请求拦截器:

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 开发环境代理:

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;
    }
  }
}

错误处理最佳实践

统一错误处理方式:

vue 实现接口调用

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自己实现下拉导航

vue自己实现下拉导航

实现下拉导航的基本思路 在Vue中实现下拉导航,可以通过结合Vue的响应式数据和事件绑定特性来完成。主要思路是利用v-show或v-if控制下拉菜单的显示与隐藏,并通过鼠标事件或点击事件触发状态变化。…

vue怎么实现

vue怎么实现

Vue 实现方法 Vue 是一个流行的前端框架,用于构建用户界面。以下是几种常见的实现方法: 数据绑定 使用 v-model 指令实现双向数据绑定,适用于表单输入元素。 <input v-m…

vue实现token

vue实现token

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

vue实现上传

vue实现上传

Vue 文件上传实现方法 使用 Vue 实现文件上传可以通过原生 HTML5 的 <input type="file"> 元素结合 Vue 的事件处理和数据绑定来实现。 基础实现步骤…

vue实现radio

vue实现radio

Vue 实现 Radio 按钮 在 Vue 中实现 Radio 按钮可以通过 v-model 进行数据绑定,结合 input 元素的 type="radio" 属性。以下是一个基本示例: <t…

vue实现队列

vue实现队列

Vue 实现队列功能 在 Vue 中实现队列功能可以通过多种方式完成,以下是几种常见的方法: 使用数组模拟队列 队列遵循先进先出(FIFO)原则,可以用数组的 push 和 shift 方法模拟入队…