Vue.js $ref not found

Viewed 463

I am trying to dynamically set the padding of an element using inline styles, based on the height of the parent. For this I am using:

<div class="stock-rating positive" ref="stockRating">
    <div class="stock-rating-start-end" v-bind:style="{ paddingTop: paddingTop }">
        <div>{{ rating.value_start }}</div>
        <div>to</div>
        <div>{{ rating.value_end }}</div>
    </div>
</div>

paddingTop will be a computed property. However, before I compute it, I have to actually access the $ref of the parent element (stockRating). But, it is not found in the computed property, even though the $refs object looks to contain it.

paddingTop : function(){
    console.log(this.$refs);
    console.log(this.$refs.stockRating);
    /*computation here*/
}

The console.log output is:

enter image description here

Why is this.$refs.stockRating undefined if this.$refs has the stockRating property, and I see it contains the correct elements as well? How do I resolve this?

2 Answers

Well your $refs.stockRating is defined AND exists but it will not exists until the component is mounted as explained here.
I didn't try it but I guess that if you try to console.log your $refs.stockRatinginside the mounted(){} component property it should not be empty

You have to tell vue that DOM is ready and component was mounted.

new Vue({
  el: "#app",
  computed: {
    itemRef() {
      console.log(this.$refs.item)
      return this.ready ? this.$refs.item : false
    }
  },
  data: () => {
    return {
      ready: false
    };
  },
  mounted() {
    this.ready = true;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <div ref="item" class="item">
    {{itemRef}}
  </div>
</div>

Related