[英]Vue.js - Unable to trigger DOM update
so I have a complex nested structure that is like so in my Vue app's data:所以我有一个复杂的嵌套结构,就像我的 Vue 应用程序的数据一样:
{
x: {
y: [{
z: {
a: 1
}
}]
}
}
Although I used v-model
in a v-for with the child property, setting .za = 2
doesn't seem to trigger this in the UI.尽管我在带有子属性的 v-for 中使用了
v-model
,但设置.za = 2
似乎并没有在 UI 中触发它。 I figured ok, must be that I'm mutating a property without alerting Vue, no biggie I just need to use Vue.set
.我想好吧,一定是我在没有警告 Vue 的情况下改变了一个属性,没什么大不了的,我只需要使用
Vue.set
。
So I tried the following:所以我尝试了以下方法:
Vue.set(app.x.y[0].z, "a", 2)
Vue.set(app.x.y[0], "z", {a:2})
Vue.set(app.x.y, 0, app.x.y[0]) // app.x.y[0] is definitely {z:{a: 2}}
Vue.set(app.x, "y", app.y)
app.x.y = app.x.y.map(_ => _)
While these all usually do the trick for me, in this case it doesn't seem to work.虽然这些通常都对我有用,但在这种情况下它似乎不起作用。 If it changes things, I'm using
v-model
instead of a traditional prop, so it would be synced back to the app.如果它改变了事情,我使用
v-model
而不是传统的道具,所以它会被同步回应用程序。 I wonder if perhaps this disassociates the app.x
and the actual data property for x.我想知道这是否会解除
app.x
和 x 的实际数据属性的关联。
I'm looking for a way to trigger a DOM update or properly set the value in Vue.我正在寻找一种方法来触发 DOM 更新或在 Vue.js 中正确设置值。 I've also tried an
app.$forceUpdate()
to no avail:/我也尝试过
app.$forceUpdate()
无济于事:/
EDIT: While I wasn't able to make Vue observe the change by itself, I found that I had a function that was populating z
after it had been initialized to {}.编辑:虽然我无法让 Vue 自己观察变化,但我发现我有一个 function 在初始化为 {} 后填充
z
。 I assume Vue set watchers on z
the moment it was initialized, and so did not observe any further changed (ie adding a
in the next line).我假设 Vue 在
z
初始化的那一刻设置了观察者,因此没有观察到任何进一步的变化(即在下一行添加a
)。 Changing this to populate every possible property on initialization, combined with any of the .set
's above and a $forceUpdate
, I was able to trigger a DOM update.更改它以在初始化时填充所有可能的属性,结合上面的任何
.set
和$forceUpdate
,我能够触发 DOM 更新。 It's a temporary workaround though and I'd really like to be able to have Vue automatically observe this update.虽然这是一个临时解决方法,但我真的希望能够让 Vue 自动观察这个更新。
You can try the vue computed property or watcher .您可以尝试vue 计算属性或 watcher 。 This will automatically detect the changed in your data and update the v-model data you have.
这将自动检测数据中的更改并更新您拥有的 v-model 数据。
In this example a change in the returned value of message will automatically be applied to the input.在此示例中,消息返回值的更改将自动应用于输入。
<input v-model="message">
computed: {
message(){
return {x:{y:[1,2,3]}}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.