vue实现get请求
使用 Vue 实现 GET 请求
在 Vue 中实现 GET 请求可以通过多种方式,常见的有使用原生 fetch、axios 或 Vue 的 $http(若配置了相关插件)。以下是几种典型方法:
使用 Axios(推荐)
Axios 是一个流行的 HTTP 客户端,支持 Promise API,适合在 Vue 中使用。
-
安装 Axios
通过 npm 或 yarn 安装:npm install axios -
在组件中发起 GET 请求
在 Vue 组件的methods或生命周期钩子(如created)中调用:import axios from 'axios'; export default { data() { return { responseData: null, error: null }; }, created() { axios.get('https://api.example.com/data') .then(response => { this.responseData = response.data; }) .catch(error => { this.error = error.message; }); } };
使用 Fetch API
原生 fetch 是浏览器提供的 API,无需额外安装。
export default {
data() {
return {
responseData: null,
error: null
};
},
created() {
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => {
this.responseData = data;
})
.catch(error => {
this.error = error.message;
});
}
};
使用 Vue Resource(已废弃)
Vue Resource 曾是官方推荐的库,但目前已不再维护。仅适用于遗留项目。
-
安装 Vue Resource
npm install vue-resource -
在入口文件中启用
import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); -
发起请求
export default { created() { this.$http.get('https://api.example.com/data') .then(response => { this.responseData = response.body; }) .catch(error => { this.error = error.message; }); } };
参数传递
若需传递查询参数,Axios 和 Fetch 的方式略有不同:
-
Axios
axios.get('https://api.example.com/data', { params: { id: 1, limit: 10 } }); -
Fetch
const params = new URLSearchParams({ id: 1, limit: 10 }); fetch(`https://api.example.com/data?${params}`);
全局配置(Axios)
可设置默认 baseURL 或拦截器,避免重复代码:

// main.js 或单独配置文件
axios.defaults.baseURL = 'https://api.example.com';
axios.interceptors.response.use(
response => response.data,
error => Promise.reject(error)
);
注意事项
- 错误处理
务必捕获请求异常,避免未处理的 Promise 错误。 - 跨域问题
若接口跨域,需后端配置 CORS 或前端通过代理解决。 - 取消请求
使用 Axios 的CancelToken或 Fetch 的AbortController取消未完成的请求。






