vue实现API调用
使用 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;
}
};






