在Vue.js中,如果你更新了一个数组,但是DOM没有相应地更新,这通常是因为Vue无法检测到数组的变化。Vue.js只能检测到以下几种数组变动:
vm.items[indexOfItem] = newValue
vm.items.length = newLength
对于其他数组变动,例如 push()
, pop()
, shift()
, unshift()
, splice()
, sort()
, reverse()
等方法,Vue.js是可以检测到的。
如果你使用了Vue无法检测到的数组变动方法,比如直接通过索引赋值,Vue将不会触发视图更新。
vm.$set
或者数组的响应式方法,例如 push
, splice
等。// 错误的做法
this.items[indexOfItem] = newValue;
// 正确的做法
this.$set(this.items, indexOfItem, newValue);
// 或者
this.items.splice(indexOfItem, 1, newValue);
vm.$forceUpdate()
方法强制Vue重新渲染组件。this.items[indexOfItem] = newValue;
this.$forceUpdate();
computed: {
computedItems() {
return this.items.map(item => {
// 对item进行处理
return item;
});
}
}
<template>
<div>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
<button @click="updateItem">Update Item</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Apple', 'Banana', 'Cherry']
};
},
methods: {
updateItem() {
const indexOfItem = 1;
const newValue = 'Blueberry';
// 正确的更新方式
this.$set(this.items, indexOfItem, newValue);
// 或者
this.items.splice(indexOfItem, 1, newValue);
}
}
};
</script>
请注意,如果你在使用Vue 3,上述方法中的一些可能会有所不同,因为Vue 3的响应式系统有所改进。在Vue 3中,你可以直接修改数组,因为Proxy已经可以检测到这些变化了。
领取专属 10元无门槛券
手把手带您无忧上云