0

I've an issue in this code

let bus = new Vue();

Vue.component('building-inner', {
 
  props: ['floors', 'queue'],
  template: `<div class="building-inner">
    <div v-for="(floor, index) in floors" class="building-floor" :ref="'floor' + (floors - index)">
      <h3>Floor #{{floors - index }}</h3>
      <button type="button" class="up" v-if="index !== floors - floors">up</button>
      <button type="button" class="down" v-if="index !== floors - 1">down</button>
    </div> 
  </div>`,
  beforeMount(){
    bus.$emit('floors', this.$refs);
  }
})

Vue.component('elevator', {
  data: {
    floorRefs: null
  },
  props: ['floors', 'queue'],
  template: `<div class="elevator" ref="elevator">
              <button type="button" v-for="(btn, index) in floors" class="elevator-btn" @click="go(index + 1)">{{index + 1}}</button>
            </div>`,
  beforeMount() {
    bus.$on('floors', function(val){
      this.floorRefs = val;
      console.log(this.floorRefs)
    })
  },
  methods: {
    go(index) {
      this.$refs.elevator.style.top = this.floorRefs['floor' + index][0].offsetTop + 'px'
    }
  }
})


new Vue({
  el: '#building',
  data: {
    queue: [],
    floors: 5,
    current: 0
  }
})
<div class="building" id="building">
  <elevator v-bind:floors="floors" v-bind:queue="queue"></elevator>
  <building-inner v-bind:floors="floors" v-bind:queue="queue"></building-inner>
</div>

I tried to access props inside $refs gets me undefined, why?

1 Answers1

3

You should use a mounted hook to get access to the refs, because on "created" event is just instance created not dom. https://v2.vuejs.org/v2/guide/instance.html

You should always first consider to use computed property and use style binding instead of using refs.

<template>
    <div :style="calculatedStyle" > ... </div>
</template>
<script>
{
//...
    computed: {
      calculatedStyle (){
        top: someCalculation(this.someProp),
        left: someCalculation2(this.someProp2),
        ....
      }
    }
}
</script>

It's bad practice to pass ref to another component, especially if it's no parent-child relationship. Refs doc Computed

tony19
  • 125,647
  • 18
  • 229
  • 307
Nikolai Borisik
  • 1,501
  • 13
  • 22