0

我在这段代码中有问题

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>

我试图访问里面的道具$refs得到我undefined,为什么?

4

1 回答 1

3

您应该使用挂载的钩子来访问引用,因为“创建”事件只是实例创建而不是 dom。 https://vuejs.org/v2/guide/instance.html

您应该始终首先考虑使用计算属性并使用样式绑定而不是使用 refs。

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

将 ref 传递给另一个组件是不好的做法,尤其是在它没有父子关系的情况下。 参考文档 计算

于 2017-11-05T08:54:34.690 回答