在 Vuejs 项目中,我的 data object 中有一个 array 并使用 v-for 将其呈现在 View 中
指令。现在,如果我更改该数组中的特定索引,Vue 会重新渲染 View 中的整个数组。有没有什么方法可以在不重新渲染整个数组的情况下查看 View 的变化?
这个问题背后的原因是我的数组的其他索引正在处理或做某事,当整个数组重新呈现在 View 中时,这些过程停止了。
最佳答案
在 Vue 1.x 中我们有 track-by="$index"
跟踪渲染数组中更改的索引。但从 2.x 版本开始,Vue 建议使用 :key
当我们用 v-for
在 View 中渲染数组时intead track-by="$index"
.但考虑一下这个打击示例:
在<template>
:
<div v-for="(doc, i) in docs" :key="i">
<h4>{{ doc.status }}</h4>
<button @click="reject(i)"> Reject </button>
</div>
在<script>
:
data: {
docs: [
{ status: 'pending' },
{ status: 'pending' },
{ status: 'pending' }
]
},
methods: {
reject(index) {
this.docs[index] = { status: 'rejected' }
}
}
在这个例子中,当我们改变一个索引时,虽然数组改变了但是我们在 View 中看不到任何变化。那是因为我们的组件之前渲染过,我们需要更新它的 View 。为此我们需要使用 this.$forceUpdate()
在我们的方法中更新组件。
reject(index) {
this.docs[index] = { status: 'rejected' }
this.$forceUpdate();
}
关于vue.js - 更改特定索引而不在 Vuejs 中重新渲染整个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63579468/