【问题标题】:Retrieve data on click in v-for loop and then loop through the data在 v-for 循环中单击时检索数据,然后循环遍历数据
【发布时间】:2020-07-16 02:03:56
【问题描述】:

我在 v-for 循环中有一个按钮,单击该按钮可检索一些数据。然后,我想在被点击的按钮下方或位置显示该数据。

<div v-for="(item, index) in items" :key="index">
  <button @click="fetchData(item.id)">Load Data</button>
  <ul v-if="THEDATALOADED">
    <li v-for="(data, index) in THEDATALOADED">
      {{ data.value }}
    </li>
  </ul>
</div>

我还想保留每个单击的按钮下方的所有数据,所以我不能只设置 this.THEDATALOADED = response.data,如果我这样做了,它会在所有 v-for 迭代中显示该数据和单击任何按钮时也会更新它们。

【问题讨论】:

  • 我认为这是一个很酷的想法。如果只有一个人可以使用数组。

标签: javascript vue.js vuejs2 vue-component v-for


【解决方案1】:

我建议你将获取的数据推送到对应的item中:

<div v-for="(item, index) in items" :key="index">
  <button @click="fetchData(item.id,index)">Load Data</button>
  <ul v-if="item.THEDATALOADED">
    <li v-for="(data, index) in item.THEDATALOADED">
      {{ data.value }}
    </li>
  </ul>
</div>

fetchData 方法中:

 fetchData(id,index){
      ....
      let tmp=this.items[index];
      tmp.THEDATALOADED=response.data;
      this.$set(this.items,index,tmp);
      ...
  }

以下运行代码说明了您的用例,在此示例中,我有一组用户,每个用户都有一些他创建的帖子,当我单击 load Posts 按钮时,它将获取对应用户的帖子:

new Vue({
  el: '#app',
  data: {
    users: [],
  },
  mounted() {

    axios.get('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        this.users = response.data
      })
  },
  methods: {
    getPosts(id, index) {
      axios.get('https://jsonplaceholder.typicode.com/posts?userId=' + id)
        .then((response) => {
          let tmp = this.users[index];
          tmp.posts = response.data;
          this.$set(this.users, index, tmp);
        })
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
</head>

<body>
  <div id="app">
    <div v-for="(user, index) in users" :key="index">
      <span>{{user.name}}</span>
      <button @click="getPosts(user.id,index)">load Posts</button>
      <ul v-if="user.posts">
        <li v-for="(post, index) in user.posts">
          {{ post.title}}
        </li>
      </ul>
    </div>
  </div>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 2011-01-29
    • 2022-01-20
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多