vue2api接口调用
时间: 2023-09-08 11:17:04 浏览: 57
在Vue 2中调用API接口,你可以使用`axios`库来发送HTTP请求。首先,确保你已经安装了`axios`库,你可以通过以下命令来安装:
```bash
npm install axios
```
接下来,在你的Vue组件中,你可以使用以下代码来调用API接口:
```javascript
import axios from 'axios';
export default {
methods: {
fetchData() {
axios.get('http://api.example.com/data')
.then(response => {
// 处理接口返回的数据
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
}
}
}
```
在上面的例子中,`fetchData`方法使用`axios.get`方法发送一个GET请求到`http://api.example.com/data`接口。在成功返回数据时,我们使用`.then`回调函数处理返回的数据,而在请求失败时,我们使用`.catch`回调函数处理错误。
当然,你也可以使用其他HTTP方法(如POST、PUT、DELETE等)来发送请求,并且可以在请求中传递参数等。你可以参考`axios`的官方文档来了解更多用法和选项:https://github.com/axios/axios