undefinederror
undefinederror

Reputation: 861

Computed property based on DOM, to update *after* render

What is the recommended way to have a computed property react to DOM property changes?

My scenario is this:
I have a computed property that is based on values found in DOM (e.g element width).
The DOM property changes as a result of the view update.
Now the computed property doesn't update as a result of DOM change.

I have made a codepen with a simplified example to illustrate the issue. In the example there I am forcing the computed property to update using a 'dummy' property that changes in the 'updated' hook.

updated(){
  console.log('updated')
  this.dummy= this.dummy * -1
},
computed:{
  width(){
    console.log('computed')
    const w = (this.$refs.square || {}).clientWidth
    return w + this.dummy * 0
  }
}

I do understand that if a property updates reacting to DOM changes, and DOM updates reacting to property changes, well, there would be no end to it.

So, is there any clean way to keep the two sync'd?

Thank you

Upvotes: 3

Views: 1176

Answers (1)

Bert
Bert

Reputation: 82459

You wouldn't normally rely on DOM properties; you would normally let the DOM be completely determined by data. That way you wouldn't have this issue.

That said, at the cost of an additional render, you could keep your properties in sync by using $nextTick.

data:{
  size:20,
  width: 20
},
methods:{
  onInput(e){
    this.size =e.target.value
    this.$nextTick(() => this.width = (this.$refs.square || {}).clientWidth)
  }
}

And just eliminate your computed entirely.

Updated pen.

Upvotes: 1

Related Questions