【发布时间】:2022-01-23 12:41:41
【问题描述】:
我在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>
【问题讨论】:
-
最少的可重现代码将帮助我们为您提供答案。
标签: javascript vue.js vuejs2 v-for