source

전체 목록을 다시 렌더링하지 않고 vue js v-for에 동적 데이터를 추가하시겠습니까?

goodcode 2022. 7. 26. 23:41
반응형

전체 목록을 다시 렌더링하지 않고 vue js v-for에 동적 데이터를 추가하시겠습니까?

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: []
    }
  }

다음으로 [Loadmore]버튼을 클릭하면 다음과 같이 API에서 데이터를 가져와 for의 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>

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}))

언급URL : https://stackoverflow.com/questions/70446528/append-dynamic-data-to-vue-js-v-for-without-rerender-the-entire-list

반응형