Using $refs in a computed property

If you need the $refs after an v-if you could use the updated() hook.

<div v-if="myProp"></div>
updated() {
    if (!this.myProp) return;
    /// this.$refs is available
},

I think it is important to quote the Vue js guide:

$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.

It is therefore not something you're supposed to do, although you can always hack your way around it.


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;
  }
})

Tags:

Vue.Js