Vue. js - JSON Данные API не отображаются при клике - PullRequest
0 голосов
/ 15 февраля 2020

У меня проблемы с моим VueJS проектом.

Я пытаюсь получить событие щелчка, чтобы показать дополнительные пользовательские данные из JSON API.

Консоль распознает событие click, но по какой-то странной причине не появляется никаких дополнительных данных, которые я пытаюсь переключить.

Я подозреваю, что метод виноват, или, возможно, что Событие click не сконфигурировано должным образом, потому что данные есть, но ничего не отображается - в консоли также нет ошибок.

Буду признателен за любые предложения!

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
    <section class="middleSection">
    <div class="container">
    <div class="row">
      <div class="col-12">
            <table class="table table-dark">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>User name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody v-for="(user, index) in users" :key="index">
                  <tr data-toggle="collapse" @click="showInfo(userInfo)">
                    <td>{{ user.name }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.email }}</td>
                  </tr>
                </tbody>
            </table>

            <div v-if="userInfo" class="card card-body">
              <div>{{ userInfo.name }}</div>
              <div>{{ userInfo.username }}</div>
              <div>{{ userInfo.adress.street }}</div>
              <div>{{ userInfo.address.suite }}</div>
              <div>{{ userInfo.address.city }}</div>
              <div>{{ userInfo.address.zipcode }}</div>
            </div>


        </div>
        </div>
        </div>
    </section>
</template>

<script>

export default {
  name: "middleSection",
  data() {
    return {
      users: [],
      userInfo: null
    }
  },

  methods: {
    showInfo(userId) {
      
      for (const user of this.users) {
        
        if (user.id == userId) {
          
          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },


  created() {
    // Fetch JSON data
              fetch('https://jsonplaceholder.typicode.com/users/')
                  .then(response => response.json())
                    .then(json => {
                    this.users = json
                  }) 
  }
}

</script>

<style>

.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
  .middleSection {
    height: 87vh;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 5vh !important;
  }
</style>

Ответы [ 2 ]

1 голос
/ 15 февраля 2020

Во-первых, вы делаете опечатку, пропуская 'd' в <div>{{ userInfo.adress.street }}</div>, во-вторых, ваш l oop должен быть в элементе <tr>, наконец, передав user.id в качестве параметра в @click="showInfo(user.id)"

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  data() {
    return {
      users: [],
      userInfo: null
    }
  },

  methods: {
    showInfo(userId) {

      for (const user of this.users) {

        if (user.id == userId) {

          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },


  created() {
    // Fetch JSON data
    fetch('https://jsonplaceholder.typicode.com/users/')
      .then(response => response.json())
      .then(json => {
        this.users = json
      })
  }
})
.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.middleSection {
  height: 87vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5vh !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

<div id="app">
  <section class="middleSection">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <table class="table table-dark">
            <thead>
              <tr>
                <th>Name</th>
                <th>User name</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody >
              <tr data-toggle="collapse" v-for="(user, index) in users" :key="index"  @click="showInfo(user.id)">
                <td>{{ user.name }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
              </tr>
            </tbody>
          </table>

          <div v-if="userInfo" class="card card-body">
            <div>{{ userInfo.name }}</div>
            <div>{{ userInfo.username }}</div>
            <div>{{ userInfo.address.street }}</div>
            <div>{{ userInfo.address.suite }}</div>
            <div>{{ userInfo.address.city }}</div>
            <div>{{ userInfo.address.zipcode }}</div>
          </div>


        </div>
      </div>
    </div>
  </section>
</div>
1 голос
/ 15 февраля 2020

Я смог воспроизвести пример без каких-либо проблем. Может быть, это была просто опечатка?

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    users: [],
    userInfo: null
  },
  methods: {
    showInfo(userId) {
      for (const user of this.users) {
        if (user.id == userId) {
          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },
  created() {
    // Fetch JSON data
    fetch('https://jsonplaceholder.typicode.com/users/')
      .then(response => response.json())
      .then(json => {
        this.users = json
      })
  }
})
.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.middleSection {
  height: 87vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5vh !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <section class="middleSection">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <table class="table table-dark">
            <thead>
              <tr>
                <th>Name</th>
                <th>User name</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody v-for="(user, index) in users" :key="index">
              <tr data-toggle="collapse" @click="showInfo(userInfo)">
                <td>{{ user.name }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
              </tr>
            </tbody>
          </table>

          <div v-if="userInfo" class="card card-body">
            <div>{{ userInfo.name }}</div>
            <div>{{ userInfo.username }}</div>
            <div>{{ userInfo.adress.street }}</div>
            <div>{{ userInfo.address.suite }}</div>
            <div>{{ userInfo.address.city }}</div>
            <div>{{ userInfo.address.zipcode }}</div>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...