我正在渲染一堆基于 Vue 数据的 HTML div(我将它们命名为单元格)。
单元格的颜色由数据中的十六进制代码决定。
鼠标悬停时,应运行一个函数来更改特定单元格的颜色。
这是数据的外观以及函数目前的工作方式:
new Vue({
el: '#app',
data: {
cells: [
{i: 1, hex: '#111111'},
{i: 2, hex: '#222222'},
{i: 3, hex: '#ffffff'}
]
},
methods: {
mouseOver: function (e){
this.cells[e.toElement.id].hex = (Math.floor(Math.random() * 16777215)).toString(16);
}
}
})
下面是渲染(在本例中)3 个单元格的 v-for 代码:
<div class='cell'
v-for="cell in cells"
:id="cell.i"
:key="cell.i"
:style="{ backgroundColor: cell.hex}"
@mouseenter="mouseOver">
</div>
但是这不起作用。
[Vue warn]: You may have an infinite update loop in a component render function.
(found in
<Root>
)
我推测这是因为每次数据更改时 Vue 都会重新渲染所有单元格,并且由于组件是新的,所以函数会再次运行。
但是我是 Vue 的新手,不确定如何解决这个问题!
非常感谢帮助!
最佳答案
您忘记在十六进制颜色代码的开头添加 #
并且您忘记将访问数组的索引减一。
此外,某些浏览器似乎不支持e.toElement
。而是使用 e.target
What is the difference between Event.target, Event.toElement and Event.srcElement?
this.cells[e.target.id-1].hex = '#' + (Math.floor(Math.random() * 16777215)).toString(16);
工作 fiddle :https://jsfiddle.net/TobiObeck/qfpkvn9L/1/
关于Vue.JS 无限重新渲染数据变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241964/