在本周工作中,碰到了一个比较棘手的问题。表格绑定的数组元素更新后,表格无法重新渲染的问题。趁着周末的时间解决一下。
<template>
<div>
<p
v-for="(item, index) in showObj.rows"
:key="index"
:style="`color:${item.color}`">
Hello World!
</p>
<button @click="handleAdd">Add</button>
<button @click="handleChange">Change</button>
<button @click="handleClear">Clear</button>
</div>
</template>
export default {
name: 'HomePage',
data() {
return {
showObj: {
rows: []
},
obj: {
rows: [{
color: 'Red'
}, {
color: 'Green'
}, {
color: 'Blue'
}]
}
}
},
methods: {
handleAdd() {
let red = Math.floor(Math.random()*256);
let green = Math.floor(Math.random()*256);
let blue = Math.floor(Math.random()*256);
this.obj.rows.push({
color: `rgb(${red},${green},${blue})`
})
},
handleClear() {
this.obj.rows = this.obj.rows.slice(0, 3);
},
handleChange() {
this.obj.rows.splice(Math.floor(Math.random() * this.obj.rows.length), 1, {
color: 'white'
})
},
},
mounted() {
this.showObj.rows = this.obj.rows;
}
}
handleClear() {
console.log(this.obj.rows === this.showObj.rows)
this.obj.rows = this.obj.rows.slice(0, 3);
console.log(this.obj.rows === this.showObj.rows)
}