当前位置:首页 > VUE

vue实现API调用

2026-01-19 02:06:18VUE

Vue 中调用 API 的方法

在 Vue 中调用 API 通常需要借助 HTTP 客户端库,例如 axiosfetch。以下是几种常见的方法:

使用 axios 调用 API

axios 是一个流行的 HTTP 客户端库,支持 Promise API,适用于浏览器和 Node.js 环境。

安装 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;
      }
    }
  },
  mounted() {
    this.fetchPosts();
  }
};

使用 fetch API

fetch 是浏览器原生提供的 API,无需额外安装库。

在 Vue 组件中使用 fetch:

export default {
  data() {
    return {
      posts: [],
      error: null
    };
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        this.posts = await response.json();
      } catch (error) {
        this.error = error.message;
      }
    }
  },
  mounted() {
    this.fetchPosts();
  }
};

封装 API 调用

为了代码复用和更好的维护性,可以将 API 调用封装成独立的服务模块。

创建 api.js 文件:

import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 1000
});

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

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

import api from '@/services/api';

export default {
  data() {
    return {
      posts: [],
      error: null
    };
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await api.getPosts();
        this.posts = response.data;
      } catch (error) {
        this.error = error.message;
      }
    }
  },
  mounted() {
    this.fetchPosts();
  }
};

使用 Vuex 管理 API 数据

对于大型应用,可以使用 Vuex 集中管理 API 调用的状态。

创建 Vuex store:

import axios from 'axios';

const state = {
  posts: [],
  error: null
};

const mutations = {
  SET_POSTS(state, posts) {
    state.posts = posts;
  },
  SET_ERROR(state, error) {
    state.error = error;
  }
};

const actions = {
  async fetchPosts({ commit }) {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      commit('SET_POSTS', response.data);
    } catch (error) {
      commit('SET_ERROR', error.message);
    }
  }
};

export default {
  state,
  mutations,
  actions
};

在 Vue 组件中调用 Vuex action:

export default {
  computed: {
    posts() {
      return this.$store.state.posts;
    },
    error() {
      return this.$store.state.error;
    }
  },
  mounted() {
    this.$store.dispatch('fetchPosts');
  }
};

处理 API 请求的加载状态

可以添加加载状态以提升用户体验。

在 Vue 组件中添加加载状态:

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

在模板中显示加载状态:

vue实现API调用

<div v-if="isLoading">Loading...</div>
<div v-else-if="error">{{ error }}</div>
<div v-else>
  <ul>
    <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
  </ul>
</div>

以上方法涵盖了 Vue 中调用 API 的常见场景,可以根据项目需求选择适合的方式。

标签: vueAPI
分享给朋友:

相关文章

vue实现密码框的包

vue实现密码框的包

Vue 密码框实现方案 在 Vue 中实现密码框功能,可以通过原生 HTML 结合 Vue 指令或使用第三方组件库完成。以下是几种常见方案: 原生 HTML + Vue 双向绑定 <t…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue筛选实现

vue筛选实现

Vue 筛选实现方法 使用计算属性实现筛选 计算属性是 Vue 中实现数据筛选的常用方式。通过定义一个计算属性,可以根据输入的条件动态过滤数据。 <template> <div…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template>…

vue实现addclass

vue实现addclass

Vue 实现动态添加 class 的方法 在 Vue 中动态添加 class 可以通过多种方式实现,以下是常见的几种方法: 使用对象语法 通过绑定一个对象到 :class,可以动态切换 class…