element ui http-request使用
时间: 2023-04-26 07:05:39 浏览: 387
Element UI 的 http-request 是一个基于 axios 封装的 HTTP 请求组件,可以方便地发送 HTTP 请求并处理响应数据。
使用 http-request 需要先在 Vue 实例中引入 Element UI 的组件:
```
import { Loading, Message } from 'element-ui';
```
然后在 Vue 实例中定义一个 http-request 方法,用于发送 HTTP 请求:
```
methods: {
httpRequest(url, method, data, successCallback, errorCallback) {
let loadingInstance = Loading.service({ fullscreen: true });
axios({
url: url,
method: method,
data: data
}).then(response => {
loadingInstance.close();
if (response.data.code === 0) {
successCallback(response.data.data);
} else {
Message.error(response.data.msg);
}
}).catch(error => {
loadingInstance.close();
errorCallback(error);
});
}
}
```
在这个方法中,我们使用了 Element UI 的 Loading 和 Message 组件来显示加载中和错误提示。我们还使用了 axios 发送 HTTP 请求,并在响应成功时调用 successCallback 回调函数,响应失败时调用 errorCallback 回调函数。
使用 http-request 方法发送 HTTP 请求时,只需要传入请求的 URL、请求方法、请求数据以及成功和失败的回调函数即可:
```
this.httpRequest('/api/user', 'post', { name: 'Tom', age: 18 }, data => {
console.log(data);
}, error => {
console.error(error);
});
```
这样就可以方便地使用 Element UI 的 http-request 组件发送 HTTP 请求了。