要请求数据并渲染,请按照以下步骤操作:
1.安装 axios
Axios 是一个常用的 JavaScript HTTP 客户端库,用于发送 HTTP 请求。在 Vue3 中,我们可以使用 Axios 发送 HTTP 请求来获取数据。
npm install axios
2.在组件中使用 Axios
定义一个函数,在该函数中使用 Axios 发送 HTTP 请求,并将返回的数据保存在组件的 data 中。然后,使用 v-for 循环渲染数据。
<template>
<div>
<ul>
<li v-for="item in list" :key="item.id">{{ item.title }}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'App',
data() {
return {
list: [],
};
},
created() {
this.getData();
},
methods: {
async getData() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
const { data } = response;
this.list = data;
} catch (error) {
console.error(error);
}
},
},
};
</script>
<style>
</style>
在该示例中,我们使用 Axios 发送一个 GET 请求来获取 JSONPlaceholder 的文章列表。一旦成功获取数据,我们将其保存在组件的 list 数据中,并在模板中使用 v-for 渲染数据。注意,我们使用了 async/await 来处理异步请求。