我在 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 获取数据的方法,然后将它们添加到 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>
最佳答案
如果从 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}))
关于javascript - 将动态数据附加到 vue js v-for 而不重新渲染整个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70446528/