Search code examples
vue.js

Using $refs in a computed property


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


Solution

  • Sometimes you just need access to a dom element to make some calculations.

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