Fetch all users and display them with vue js

对着背影说爱祢 提交于 2019-12-09 23:53:44

问题


I am very new to Vue js and I am now trying to output all the users in a table by fetching them with an ajax call. I get the users with no issue but then when I try to set the data.user with the new data I get an error saying the property or method users is not defined. This is my user list components:

<template>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">List of users</div>
                <div class="panel-body">
                    <table class="table">
                        <thead>
                          <tr>
                            <th>Firstname</th>
                            <th>Lastname</th>
                            <th>Email</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="user in users">
                            <td>user.name</td>
                            <td>user.lastaname</td>
                            <td>user.email</td>
                          </tr>
                      </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</template>


<script>
export default {

    data: function () {
        return {
          users: []
        }
    },

    mounted() {
        axios.get('/users')
            .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            console.log(error.message);
        });
    },

}
</script>

回答1:


Try this

<script>
export default {

    data: function () {
        return {
          users: []
        }
    },

    methods: {

      getUsers: function() {

        var app = this;

         axios.get('/users')
            .then(function (response) {
            app.users = response.data;
        })
        .catch(function (error) {
            console.log(error.message);
        });

      }

    },

    created() {
      this.getUsers();
    },

    }

ES6 Syntax

  getUsers() {

     axios.get('/users')
      .then((response) => this.users = response.data)
      .catch((error) => console.log(error.message))

  }


来源:https://stackoverflow.com/questions/47111197/fetch-all-users-and-display-them-with-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!