我正在学习 VueJs,我正在尝试找出解决我问题的最佳方案。
问题是,如果我多次调用 this.$set()
,只有最后一次调用会被注册。
我尝试过使用 setTimeout
(就像在过去的 angular1 时代一样),但它仍然不起作用。
然后我尝试使用 Vue.$nextTick()
应该重新渲染 DOM,但似乎数据添加到对象中的速度不够快。
查看演示 here .
多次按下每个按钮,您会发现大部分时间都跳过了第一条日志。
最佳答案
Date.now()
的使用不正确。
它发生得如此之快,以至于时间戳有时不会在 2 个 this.$set
操作之间发生变化,因此您可以覆盖 logs
对象中的值。
当我点击第一个按钮时,查看 Date.now()
的日志
1509287060410 // first result of Date.now.
1509287060412 // Second Result of Date.now - this time, it's different from the first attempt, so 2 different entries will be created.
1509287061243 // another click on the button - timestamp has changed obviosuly.
1509287061243 // Javascript did the second Set so far, that time timestamp didn't even changed yet. thus, it overrides the value of the second entry
所以这个日志,4 个this.$set
操作的结果,创建了这个logs
对象:
{
1509287060410:"I was clicked!"
1509287060412:"I was clicked again!"
1509287061243:"I was clicked again!"
}
最后一个 1509287061243
属性被覆盖。
您必须确保this.$set
(函数的第二个参数)的键在您每次调用时都是不同的。
查看我的新代码建议:
data() {
return {
title: 'Multiple Vue.set() not updating object/DOM',
logs: {},
index: 0
}
},
methods: {
log: function(data) {
console.log(Date.now())
this.index += 1
this.$set(this.logs, this.index, data)
},
关于javascript - 多个 Vue.set() 不更新对象/DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000988/