英文:
What could be causing my Vue.js fetch API code to not display fake users as expected?
问题
Here is the translated code portion:
<body class="container bg-warning">
<h1>
Test Users via REST
</h1>
<p>
Reference to the site reqres.in responsible for providing test data,
in JSON format, for free.
</p>
<div id="usuarios" class="container-fluid">
<div class="row">
<div class="card col-3 p-2 m-3" v-for="(user,index) in users" v-bind:key="index">
<div class="card-body">
<img class="card-img-top" :src="user.avatar">
</img>
<h1>
{{ user.first_name }} + {{ user.last_name }}
</h1>
<p>
{{ user.email }}
</p>
</div>
</div>
</div>
</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {
users: []
}
},
methods: {
loadUsers() {
fetch('https://reqres.in/api/users?per_page=10').then(res => res.json()).then(data => this.users = data.data);
}
},
mounted() {
this.loadUsers()
}
}).mount('#usuarios')
</script>
</body>
</html>
Please note that I've translated the code while keeping the structure and placeholders intact.
英文:
<body class="container bg-warning">
<h1>
Usuários de Teste via REST
</h1>
<p>
referência ao site reqres.in responsável por fornecer os dados de teste,
no formato JSON, de forma gratuita
</p>
<div id="usuarios" class=" container-fluid">
<div class="row">
<div class="card col-3 p-2 m-3" v-for="(user,index) in users" v-bind:key="index">
<div class=" card-body">
<img class="card-img-top" src={{user.avatar}}>
</img>
<h1>
{{user.first_name}} + {{user.last_name}}
</h1>
<p>
{{user.email}}
</p>
</div>
</div>
</div>
</div>
<script>
const {
createApp
} = Vue
createApp({
data() {
return {
users: []
}
},
methods: {
loadUsers() {
fetch('https://reqres.in/api/users?per_page=10').then(res =>res.json()).then(data =>users = (data.data));
}
},
mounted() {
this.loadUsers()
}
},
).mount('#usuarios')
</script>
</body>
</html>"
//i tried changing the method loadUsers multiple times. this is the way that dont show errors .
//however still does not work. the goal is to load the array users with the data from the fetch. and use the user in the vue to show the information from users
答案1
得分: 0
在组件实例内部,您需要使用 this
引用数据和方法(在HTML部分不需要,因为Vue很智能!)
then(data => this.users = (data.data));
确保您在代码中使用此脚本标签来使用来自CDN的Vue(我假设您已经有它,但它没有在您的代码中!)
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
就像官方文档中的示例一样:
英文:
Inside the component instance you need to references the data and methods by using this
(it's not needed in the HTML part because Vue is clever!)
then(data => this.users = (data.data));
Make sure you have this script tag to use Vue from a CDN (I assume you have it but it's not on your code!)
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
Like in the example on the official doc:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论