vue中this.$api的使用例子
时间: 2023-12-12 16:03:32 浏览: 42
假设我们有一个后端 API,可以获取用户列表。我们可以在 Vue.js 组件中使用 `this.$api` 来调用这个 API,示例代码如下:
```vue
<template>
<div>
<h1>用户列表</h1>
<ul>
<li v-for="user in userList" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
userList: []
};
},
created() {
this.fetchUserList();
},
methods: {
async fetchUserList() {
try {
const response = await this.$api.get('/users');
this.userList = response.data;
} catch (error) {
console.error(error);
}
}
}
};
</script>
```
在上面的例子中,我们首先定义了一个 `userList` 数据,用来存储从后端 API 中获取到的用户列表。在组件的 `created` 钩子函数中,我们调用了 `fetchUserList` 方法来获取用户列表。在 `fetchUserList` 方法中,我们使用 `this.$api` 来调用后端 API,获取用户列表的接口是 `/users`,使用 `get` 方法来发送 HTTP GET 请求。如果请求成功,我们就将获取到的用户列表赋值给 `userList` 数据,否则打印错误信息。最终,在模板中使用 `v-for` 指令来渲染用户列表。