如何在不重新渲染整个列表的情况下向Vue.js的v-for指令追加动态数据?

3

我有以下vue 2模板(简化版):

<template>
 <div>
  <div v-for="(data, index) in allData" :key="index">
     <app-collection :data="data" :index="index"></app-collection>
  </div>
 </div>
</template>

以下是我的数据:

data: function(){
    return {
      allData: []
    }
  }

我有一个"加载更多"按钮,当我点击它时,会调用一个从API获取数据的方法,然后在forEach循环中将它们添加到allData中,代码如下:

this.allNFT.push({name: "name 1", age: 25"})

我的问题是每次添加新数据时,它会重新渲染整个列表而不仅仅是在末尾添加新数据。

有没有办法避免这种情况,只是追加新数据?

以下是我简化后的代码全局概述(我还没有在线API):

<template>
  <div>
    <div id="collectionList" class="form-group" v-else>
      <div class="row">
        <div class="col-lg-4" v-for="(data, index) in allData" :key="data.assetId+'_'+index">
          <app-collection :data="data" :index="index"></app-collection>
        </div>
      </div>
      <button class="btn btn-primary" v-if="loadMore" @click="getallData()">Load more</button>
      <div v-else class="text-center">{{ allData.length ? 'All data loaded' : 'No data found' }}</div>
    </div>
  </div>
</template>
<script>

import collection from '@/components/content/collection/collection.vue'


export default {
  data: function(){
    return {
      loadMore: true,
      allData: [],
      perpage: 25,
      currentPage: 1
    }
  },
  components: {
    'app-collection': collection
  },
  created: function(){
    this.init()
  },
  methods: {
    init: async function(){
      await this.getallData()
    },
    getallData: async function(){
      let filtered = {
          "page": this.currentPage,
          "perpage": this.perpage,
        }
      try{
        let getData = await fetch(
          "http://localhost:3200/secondary/paginate-filter",
          {
            method: 'post',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(
              filtered
            )
          }
        )
        getData = await getData.json()
        if(getData.length){
          getData.forEach((elm) => {
            this.allData.push({name: elm.name, age: elm.age})
          })
        }
        this.currentPage++
        if(getData.length < this.perpage){
          this.loadMore = false
        }
      }catch(e){
        console.log(e)
      }
    },
  }
};
</script>

一个最小化可重现的代码会帮助我们为您提供答案。 - skr
1个回答

3
如果你从API中只收到下一页的数据,你可以使用:

this.allData.push(...getData);

//If you want to change response data
this.allData.push(...getData.map(d => ({name: d.name, age: d.age})))


如果您的服务器返回了前一页的数据,则需要重新分配数据。
this.allData = getData.map(d => ({name: d.name, age: d.age}))

服务器仅返回新数据,然后我将它们附加到所有数据中,但它会重新渲染整个页面,而我只想在末尾添加新数据。 - Christophe
这样的话,第一种方法会帮助你。 - Farhod Nematov
getData没有返回我想要的结构,所以我先通过forEach遍历来推送一个自定义对象。 - Christophe
因为列表中的每个组件 <app-collection /> 都会重新加载其动态数据。 - Christophe
你在子组件中修改数据了吗? - Farhod Nematov
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接