vue 怎么实现api
在 Vue 中调用 API 的方法
使用 Axios 发起 HTTP 请求
安装 Axios 依赖:
npm install axios
在 Vue 组件中引入并使用:
import axios from 'axios';
export default {
methods: {
fetchData() {
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
}
}
}
使用 Fetch API
现代浏览器内置的 Fetch API 可以直接使用:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
封装 API 服务
创建单独的 API 服务文件(如 api.js):
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000
});
export default {
getData() {
return apiClient.get('/data');
},
postData(payload) {
return apiClient.post('/data', payload);
}
}
在 Vuex 中集成 API 调用
对于状态管理,可以在 Vuex actions 中调用 API:
actions: {
async fetchData({ commit }) {
try {
const response = await axios.get('/api/data');
commit('SET_DATA', response.data);
} catch (error) {
console.error(error);
}
}
}
使用 async/await 语法
更现代的异步处理方式:
methods: {
async loadData() {
try {
const response = await axios.get('/api/data');
this.data = response.data;
} catch (error) {
console.error(error);
}
}
}
处理跨域问题
在开发环境中配置代理(vue.config.js):
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
添加请求拦截器
全局处理请求和响应:
axios.interceptors.request.use(config => {
// 添加 token 等操作
config.headers.Authorization = `Bearer ${token}`;
return config;
}, error => {
return Promise.reject(error);
});
响应拦截器
统一处理响应:
axios.interceptors.response.use(response => {
// 统一处理数据
return response.data;
}, error => {
// 统一错误处理
return Promise.reject(error);
});






