Vue - Заполните таблицу с Axios - PullRequest
1 голос
/ 17 июня 2019

Я пытаюсь заполнить таблицу с помощью axios и vue, например:

    <div class="container  h-100">
        <div class="row h-100 justify-content-center align-items-center">
            <table class="table table-striped table-bordered table-hover">
                <thead class="thead-dark">
                    <tr>
                        <th>#</th>
                        <th>First</th>
                        <th>Last</th>
                        <th>Handle</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in users">
                        <td>{{user.name}}</td>
                        <td>{{user.username}}</td>
                        <td>{{user.email}}</td>
                        <td>{{user.phone}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    var users;
    axios.get('https://jsonplaceholder.typicode.com/users')
        .then(function (response) {
            users = response['data'];
        })
        .catch(function (error) {
            console.log(error);
        })
</script>

Проблема в том, что {{user.name}} возвращает '{{user.name}}', не показывает реальные данные. Кто-нибудь знает, как я могу использовать vue для отображения данных массива в таблице?

UPDATE

Я обновил этот код, но просмотр по-прежнему пуст. Если я верну this.users в сценарии, вернем объект со значениями.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <title>Tabla</title>
        <style>
            body,
            html {
                height: 100%;
            }
        </style>
    </head>

    <body>
        <div id="tabla">
            <div class="container  h-100">
                <div class="row h-100 justify-content-center align-items-center">
                    <table class="table table-striped table-bordered table-hover text-center">
                        <thead class="thead-dark">
                            <tr>
                                <th>Name</th>
                                <th>Username</th>
                                <th>Email</th>
                                <th>Phone</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="user in users">
                                <td>{{user.name}}</td>
                                <td>{{user.username}}</td>
                                <td>{{user.email}}</td>
                                <td>{{user.phone}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        new Vue({
            el: '#tabla',
            data: {
                users: [],
            },
            created: function () {
                this.load();
            },
            methods: {
                load: function () {
                    axios
                        .get('https://jsonplaceholder.typicode.com/users')
                        .then(function (response) {
                            this.users = response.data;
                        })
                        .catch(function (error) {
                            console.log(error);
                        })
                }
            }
        })
    </script>

</html>

Ответы [ 3 ]

1 голос
/ 17 июня 2019

Обновление

Проблема с this в вашем axios api обратном вызове.

Это неправильное место для объяснения this очень объяснительным.

В простом контексте - this - это объект, свойство которого function.И в вашем случае this получите window объект, поскольку вы используете function, который не lexically ограничен.Чтобы сделать это lexically scoped Используйте ES6 Arrow fn

new Vue({
  el: "#app",
  data() {
  	return {
    	users: []
    }
  },
  mounted: function() {
      axios
        .get('https://jsonplaceholder.typicode.com/users')
        .then(response => {
          this.users = response.data
        })
        .catch(function (error) {
          console.log(error);
        })
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">

  <table>
      <thead class="thead-dark">
                    <tr>
                        <th>#</th>
                        <th>First</th>
                        <th>Last</th>
                        <th>Handle</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in users" :key="user.email">
                        <td>{{user.name}}</td>
                        <td>{{user.username}}</td>
                        <td>{{user.email}}</td>
                        <td>{{user.phone}}</td>
                    </tr>
                </tbody>
  </table>
</div>

Вам нужно создать vue instance, который привязывает к нему ваш html.

Допустим, у вас есть html, который имеетid = app

<div id="app">
  {{ message }}
</div>

Теперь, если вы хотите, чтобы этот кусок HTML использовал vue, вам нужно связать его.

var app = new Vue({
  el: '#app', // This property el binds the container #app
  data: {
    message: 'Hello Vue!' // here you create your data values you want to use
  }
})

Однако я бы посоветовал вам просмотреть vue отличная документация перед использованием - Vue JS

1 голос
/ 17 июня 2019

Вы не определяете users в экземпляре vue. Вы должны создать экземпляр vue и определить users в части data.

<body>
  <div id="app">
    // Paste all of your html in here
  </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  new Vue({
    el: '#app',
    data: {
      users: []
    },
    mounted: function() {
      axios
        .get('https://jsonplaceholder.typicode.com/users')
        .then(function (response) {
          this.users = response['data'];
        })
        .catch(function (error) {
          console.log(error);
        })
    }
  })
</script>
0 голосов
/ 17 июня 2019

Правильно ли вы инициировали Vue?

Ознакомьтесь с этой официальной документацией.https://vuejs.org/v2/guide/index.html

Если вы инициировали Vue в другом файле, и это только определение компонента, вам все равно нужно следовать определению компонента.И вызовите Axios внутри жизненного цикла монтирования и определите пользователей как данные или данные.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...