vue请求后端接口的方式
时间: 2023-10-27 12:10:45 浏览: 41
Vue 请求后端接口的方式一般有两种:
1. 使用 Vue 自带的 HTTP 模块发送请求
Vue 自带了一个 HTTP 模块,可以通过该模块发送请求。首先需要在 Vue 实例中引入该模块:
```
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$http = axios;
```
然后在组件中就可以使用 this.$http 发送请求了:
```
this.$http.get('/api/users').then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
```
2. 使用第三方库发送请求
除了使用 Vue 自带的 HTTP 模块发送请求,也可以使用第三方库,如 Axios 或 Fetch。使用 Axios 的示例代码如下:
```
import axios from 'axios';
axios.get('/api/users').then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
```
需要注意的是,如果要在 Vue 组件中使用 Axios,可以将其挂载到 Vue 原型上,这样就可以在组件中使用 this.$axios 发送请求了:
```
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios;
```
然后在组件中就可以使用 this.$axios 发送请求了:
```
this.$axios.get('/api/users').then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
```