vue2 接口请求回来 渲染组件
时间: 2025-06-23 16:25:51 浏览: 10
### Vue2 中使用 Axios 或 Fetch 进行 API 请求并渲染组件
#### 使用 Axios 发起请求并在数据返回后更新组件状态
在 Vue 2 中,可以通过 `mounted` 生命周期钩子发起 HTTP 请求,并通过响应来设置组件的状态。下面是一个完整的例子:
```javascript
<template>
<div v-if="loading">Loading...</div>
<ul v-else>
<li v-for="(post, index) in posts" :key="index">
{{ post.title }}
</li>
</ul>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
loading: true,
posts: [],
error: null
};
},
mounted() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data;
this.loading = false; // 当获取到数据时停止加载动画
})
.catch(error => {
console.error("There was an error fetching the posts!", error);
this.error = "无法加载帖子";
this.loading = false;
});
}
};
</script>
```
此代码片段展示了如何利用 `axios` 来调用 RESTful API 并处理成功和失败的情况[^1]。
#### 使用 Fetch API 实现相同功能
如果偏好不依赖额外库,则可以直接采用浏览器内置的 `fetch()` 函数实现同样的逻辑:
```javascript
<template>
<div v-if="loading">Loading...</div>
<ul v-else>
<li v-for="(post, index) in posts" :key="index">{{ post.title }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
loading: true,
posts: []
};
},
async mounted() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) throw new Error('Network response was not ok');
const json = await response.json();
this.posts = json;
} catch (error) {
console.error("Fetch failed", error.message);
} finally {
this.loading = false;
}
}
};
</script>
```
这段代码同样实现了向服务器发出 GET 请求的功能,并且当接收到有效响应后将结果显示出来;同时,在任何错误发生的情况下都会显示友好的提示信息。
阅读全文
相关推荐


















