更改特定索引而不在Vuejs中重新渲染整个数组 [英] Change specific index without re-render whole array in Vuejs
问题描述
在Vuejs 项目中,我的数据对象 中有一个数组,并使用v-for 将其呈现在视图中
指令.现在,如果我更改该数组中的特定索引,Vue 会在视图中重新渲染整个数组.有没有办法在不重新渲染整个数组的情况下查看视图中的变化?
这个问题背后的原因是我的数组的其他索引正在处理或做一些事情,当整个数组在视图中重新渲染时,这些进程会停止.
在 Vue 1.x 中,我们有 track-by="$index"
来跟踪渲染数组中更改的索引.但是从 2.x 版本开始,Vue 建议在我们使用 v-for
而不是 track-by=$index"<在视图中渲染数组时使用
:key
/代码>.但请考虑这个打击示例:
在中:
<h4>{{ doc.status }}</h4><button@click="reject(i)">拒绝按钮>
在 中:
数据:{文档:[{状态:'待定'},{状态:'待定'},{ 状态:'待定' }]},方法: {拒绝(索引){this.docs[index] = { status: 'rejected' }}}
在这个例子中,当我们改变一个索引时,虽然数组发生了变化,但我们在视图中看不到任何变化.那是因为我们的组件之前渲染过,我们需要更新它的视图.为此,我们需要在我们的方法中使用 this.$forceUpdate()
来更新组件.
拒绝(索引){this.docs[index] = { status: 'rejected' }this.$forceUpdate();}
In a Vuejs project, I have an array in my data object and render it in view with a v-for
directive. now if I change a specific index in that array, Vue re-render the whole array in view. is there any way to see changes in view without re-render the whole array?
the reason behind this question is that other indexes of my array processing or doing something and when the whole array re-render in view, these processes are stopped.
In Vue 1.x we have track-by="$index"
to track changed index in rendered array. but since version 2.x, Vue suggest using :key
when we rendering array in view with v-for
intead track-by="$index"
. but consider this blow example:
In <template>
:
<div v-for="(doc, i) in docs" :key="i">
<h4>{{ doc.status }}</h4>
<button @click="reject(i)"> Reject </button>
</div>
In <script>
:
data: {
docs: [
{ status: 'pending' },
{ status: 'pending' },
{ status: 'pending' }
]
},
methods: {
reject(index) {
this.docs[index] = { status: 'rejected' }
}
}
in this example, when we change an index, Although array changes but we can't see any change in view. that's because our component rendered before and we need to update its view. for this we need to use this.$forceUpdate()
in our method to update the component.
reject(index) {
this.docs[index] = { status: 'rejected' }
this.$forceUpdate();
}
这篇关于更改特定索引而不在Vuejs中重新渲染整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!