Vue.js 是一种流行的前端 JavaScript 框架,用于构建用户界面和单页应用程序。获取后端数据是 Vue.js 应用程序中的一个常见任务,通常通过 HTTP 请求来实现。以下是一些基础概念和相关信息:
以下是一个使用 Vue 3 和 fetch
API 获取后端数据的简单示例:
<template>
<div>
<h1>用户列表</h1>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const users = ref([]);
onMounted(async () => {
try {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
users.value = data;
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
});
return { users };
}
};
</script>
JSON.parse
解析 JSON 数据,并添加错误处理逻辑。通过以上方法和示例代码,你可以在 Vue.js 应用程序中有效地获取和处理后端数据。
领取专属 10元无门槛券
手把手带您无忧上云