当前位置:首页 > 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 调用封装成独立的服务模块。

vue实现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:

vue实现API调用

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

在模板中显示加载状态:

<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实现a4打印模板

vue实现a4打印模板

使用Vue实现A4打印模板 在Vue中实现A4打印模板需要结合CSS的打印样式和Vue的模板渲染能力。以下是具体实现方法: 设置A4纸张尺寸 在CSS中定义A4纸张的标准尺寸(210mm × 297…

vue 实现blog

vue 实现blog

Vue 实现博客的基本步骤 使用 Vue 实现博客可以分为前端和后端两部分,前端使用 Vue.js 框架,后端可以选择 Node.js、Python 或其他服务端语言。以下是一个基于 Vue 的博客实…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基…

vue实现复选

vue实现复选

Vue 实现复选框 在 Vue 中实现复选框可以通过 v-model 指令绑定数据,同时结合 input 元素的 type="checkbox" 属性来实现。以下是几种常见的实现方式: 单个复选框…

vue实现换肤

vue实现换肤

使用 CSS 变量实现换肤 在 Vue 项目中,可以通过 CSS 变量(Custom Properties)动态切换主题色。CSS 变量可以在运行时修改,适合实现换肤功能。 定义全局 CSS 变量:…

vue 实现长按

vue 实现长按

实现长按功能的基本思路 在Vue中实现长按功能,通常需要监听元素的mousedown或touchstart事件,启动一个计时器。当用户按住元素超过设定的时间阈值时,触发长按回调函数。如果在时间阈值内触…