Why doesn't my Vue.js fetch API code display virtual users correctly?
P粉982009874
P粉982009874 2023-09-14 23:50:21
0
1
638

<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>
" //I tried changing the loadUsers method multiple times and this is the way it doesn't get the error. //However, still doesn't work. The goal is to use fetch to load the users array from the data and use user to display user information in vue

P粉982009874
P粉982009874

reply all(1)
P粉903052556

Inside the component instance you need to reference the data and methods using this (Not needed in the HTML part, because Vue is smart!)

then(data => this.users = (data.data));

Make sure you have this script tag to use Vue from the CDN (I'm assuming you already have it, but it's not in your code!)

Just like the example in the official documentation:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template