当前位置:首页 > VUE

vue实现API调用

2026-02-19 18:29:04VUE

使用 Vue 实现 API 调用的方法

使用 Axios 进行 API 调用

安装 Axios 依赖:

npm install axios

在 Vue 组件中引入并使用 Axios:

import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      error: null
    };
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        this.posts = response.data;
      } catch (error) {
        this.error = error.message;
      }
    }
  },
  created() {
    this.fetchPosts();
  }
};

使用 Vue Resource(已废弃但可用)

安装 Vue Resource:

npm install vue-resource

在 main.js 中引入:

import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

组件中使用:

export default {
  data() {
    return {
      users: []
    };
  },
  created() {
    this.$http.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        this.users = response.body;
      });
  }
};

使用 Fetch API

直接使用浏览器原生 Fetch API:

export default {
  data() {
    return {
      todos: []
    };
  },
  methods: {
    fetchTodos() {
      fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(data => {
          this.todos = data;
        });
    }
  },
  mounted() {
    this.fetchTodos();
  }
};

使用 async/await 语法

结合 async/await 使代码更清晰:

export default {
  data() {
    return {
      comments: []
    };
  },
  methods: {
    async getComments() {
      const response = await fetch('https://jsonplaceholder.typicode.com/comments');
      this.comments = await response.json();
    }
  },
  created() {
    this.getComments();
  }
};

配置全局 API 基础 URL

在 Axios 中配置全局基础 URL:

// 在 main.js 或单独配置文件中
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

处理 API 错误

完整的错误处理示例:

async fetchData() {
  try {
    const response = await axios.get('/endpoint');
    if (response.status !== 200) {
      throw new Error('Network response was not ok');
    }
    this.data = response.data;
  } catch (error) {
    console.error('Error fetching data:', error);
    this.error = 'Failed to load data. Please try again later.';
  }
}

使用 Vuex 管理 API 状态

在 Vuex store 中处理 API 调用:

// store.js
import axios from 'axios';

export default new Vuex.Store({
  state: {
    products: []
  },
  mutations: {
    SET_PRODUCTS(state, products) {
      state.products = products;
    }
  },
  actions: {
    async fetchProducts({ commit }) {
      const response = await axios.get('/api/products');
      commit('SET_PRODUCTS', response.data);
    }
  }
});

组件中使用 Vuex action:

export default {
  computed: {
    products() {
      return this.$store.state.products;
    }
  },
  created() {
    this.$store.dispatch('fetchProducts');
  }
};

使用拦截器

Axios 请求/响应拦截器示例:

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 在发送请求前做些什么
    config.headers['X-Custom-Header'] = 'foobar';
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response;
  },
  error => {
    // 对响应错误做点什么
    if (error.response.status === 401) {
      // 处理未授权情况
    }
    return Promise.reject(error);
  }
);

封装 API 服务

创建独立的 API 服务文件:

// api.js
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
});

export default {
  getPosts() {
    return apiClient.get('/posts');
  },
  createPost(post) {
    return apiClient.post('/posts', post);
  }
};

在组件中使用封装的服务:

import api from '@/services/api';

export default {
  data() {
    return {
      posts: []
    };
  },
  async created() {
    const response = await api.getPosts();
    this.posts = response.data;
  }
};

vue实现API调用

标签: vueAPI
分享给朋友:

相关文章

vue实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue实现muli

vue实现muli

Vue 实现多语言(i18n)支持 在 Vue 项目中实现多语言(i18n)功能,通常使用 vue-i18n 插件。以下是具体实现步骤: 安装 vue-i18n npm install vue-i…

vue 实现级联

vue 实现级联

Vue 实现级联选择器 级联选择器(Cascader)常用于省市区选择、分类选择等场景。Vue 中可以通过 Element UI、Ant Design Vue 等 UI 库实现,也可以手动封装。 使…

简单实现vue

简单实现vue

Vue 的基本实现 创建一个简单的 Vue 应用需要引入 Vue 库,并编写基本的模板和数据绑定逻辑。 <!DOCTYPE html> <html lang="en"> &l…

vue实现键盘

vue实现键盘

Vue 实现键盘功能 在Vue中实现键盘功能通常涉及监听键盘事件、处理输入以及渲染虚拟键盘界面。以下是几种常见的实现方式: 监听键盘事件 通过@keydown或@keyup指令监听键盘事件,适用于需…

jquery实现vue

jquery实现vue

jQuery 和 Vue.js 是两种不同理念的前端工具,jQuery 以 DOM 操作和事件驱动为核心,而 Vue.js 是数据驱动的现代化框架。如果想用 jQuery 实现类似 Vue 的功能(如…