简体   繁体   中英

Vue.js - Unable to trigger DOM update

so I have a complex nested structure that is like so in my Vue app's data:

{
  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. I figured ok, must be that I'm mutating a property without alerting Vue, no biggie I just need to use 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. I wonder if perhaps this disassociates the app.x and the actual data property for x.

I'm looking for a way to trigger a DOM update or properly set the value in Vue. I've also tried an app.$forceUpdate() to no avail:/

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 {}. 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). 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. It's a temporary workaround though and I'd really like to be able to have Vue automatically observe this update.

You can try the vue computed property or watcher . This will automatically detect the changed in your data and update the v-model data you have.

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]}}
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM