vue 怎么实现api
在Vue中实现API调用
Vue中调用API通常使用axios或fetch等HTTP客户端库,结合Vue的生命周期钩子或状态管理(如Vuex/Pinia)完成数据交互。以下是具体实现方法:
安装axios
通过npm或yarn安装axios库:
npm install axios
# 或
yarn add axios
基础API调用示例
在Vue组件中直接调用API:
import axios from 'axios';
export default {
data() {
return {
posts: [],
error: null
};
},
created() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data;
})
.catch(error => {
this.error = error.message;
});
}
};
封装API模块
将API请求封装为独立模块(如api.js),便于复用:
// api.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000
});
export const fetchPosts = () => api.get('/posts');
export const createPost = (data) => api.post('/posts', data);
在组件中使用:

import { fetchPosts } from '@/api';
export default {
async mounted() {
try {
const response = await fetchPosts();
this.posts = response.data;
} catch (error) {
console.error(error);
}
}
};
结合Vuex/Pinia管理状态
以Pinia为例(Store中调用API):
// stores/postStore.js
import { defineStore } from 'pinia';
import { fetchPosts } from '@/api';
export const usePostStore = defineStore('post', {
state: () => ({
posts: [],
loading: false
}),
actions: {
async loadPosts() {
this.loading = true;
try {
const response = await fetchPosts();
this.posts = response.data;
} finally {
this.loading = false;
}
}
}
});
组件中调用:
import { usePostStore } from '@/stores/postStore';
export default {
setup() {
const postStore = usePostStore();
postStore.loadPosts();
return { postStore };
}
};
拦截器配置
全局拦截器(如添加Token):

// api.js
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
错误处理
统一错误处理逻辑:
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
router.push('/login');
}
return Promise.reject(error);
}
);
使用环境变量
通过.env文件管理API基础路径:
VUE_APP_API_URL=https://api.example.com
代码中引用:
baseURL: process.env.VUE_APP_API_URL
注意事项
- 跨域问题:开发时需配置代理(
vue.config.js中devServer.proxy)。 - 取消请求:使用
AbortController或axios.CancelToken避免内存泄漏。 - TypeScript支持:为API响应定义类型接口,增强类型安全。






