Using $refs in a computed property

ghz 1years ago ⋅ 7450 views

Question

How do I access $refs inside computed? It's always undefined the first time the computed property is run.


Answer

Going to answer my own question here, I couldn't find a satisfactory answer anywhere else. Sometimes you just need access to a dom element to make some calculations. Hopefully this is helpful to others.

I had to trick Vue to update the computed property once the component was mounted.

Vue.component('my-component', {
  data(){
    return {
      isMounted: false
    }
  },
  computed:{
    property(){
      if(!this.isMounted)
        return;
      // this.$refs is available
    }
  },
  mounted(){
    this.isMounted = true;
  }
})