当前位置:首页 > 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实现下拉框删除

vue实现下拉框删除

Vue 实现下拉框删除功能 在Vue中实现下拉框的删除功能通常涉及以下步骤: 数据绑定与渲染 在Vue组件中定义数据数组用于存储下拉框选项: data() { return {…

vue实现骰子

vue实现骰子

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

vue 组件实现

vue 组件实现

Vue 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{{…

vue实现双向

vue实现双向

Vue 实现双向绑定的方法 Vue 的双向绑定主要通过 v-model 指令实现,它结合了数据绑定和事件监听,适用于表单元素(如 input、select、textarea 等)。以下是几种常见的实现…

vue实现curd

vue实现curd

Vue实现CRUD操作 初始化Vue项目 使用Vue CLI创建新项目,安装必要依赖如axios用于HTTP请求 vue create crud-demo cd crud-demo npm ins…

vue实现注册

vue实现注册

Vue 实现注册功能 注册功能通常涉及前端表单、数据验证、与后端 API 的交互等步骤。以下是一个完整的 Vue 实现注册功能的方案。 创建注册表单 使用 Vue 的模板语法创建注册表单,包含用户…