首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue `$refs`问题

Vue `$refs`问题
EN

Stack Overflow用户
提问于 2017-11-05 16:41:44
回答 1查看 1.2K关注 0票数 0

我在这段代码中有一个问题

代码语言:javascript
复制
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
  }
})
代码语言:javascript
复制
<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 gets me undefined内部的道具,为什么?

EN

回答 1

Stack Overflow用户

发布于 2017-11-05 16:54:35

你应该使用一个挂载的钩子来访问refs,因为在" created“事件上只创建了一个实例,而不是dom。https://vuejs.org/v2/guide/instance.html

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

代码语言:javascript
复制
<template>
    <div :style="calculatedStyle" > ... </div>
</template>
<script>
{
//...
    computed: {
      calculatedStyle (){
        top: someCalculation(this.someProp),
        left: someCalculation2(this.someProp2),
        ....
      }
    }
}
</script>

将ref传递给另一个组件是不好做法,特别是在它没有父子关系的情况下。Refs doc Computed

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47119709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档