vue实现API调用
Vue 中调用 API 的方法
在 Vue 中调用 API 通常需要借助 HTTP 客户端库,例如 axios 或 fetch。以下是几种常见的方法:
使用 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();
}
};
在模板中显示加载状态:
<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 的常见场景,可以根据项目需求选择适合的方式。






