[英]Vue.js $ref not found
I am trying to dynamically set the padding of an element using inline styles, based on the height of the parent.我正在尝试根据父级的高度使用内联 styles 动态设置元素的填充。 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. paddingTop
将是一个计算属性。 However, before I compute it, I have to actually access the $ref of the parent element ( stockRating
).但是,在我计算它之前,我必须实际访问父元素 (
stockRating
) 的 $ref 。 But, it is not found in the computed property, even though the $refs object looks to contain it.但是,在计算属性中找不到它,即使 $refs object 看起来包含它。
paddingTop : function(){
console.log(this.$refs);
console.log(this.$refs.stockRating);
/*computation here*/
}
The console.log
output is: console.log
output 是:
Why is this.$refs.stockRating
undefined if this.$refs
has the stockRating
property, and I see it contains the correct elements as well?如果
this.$refs
refs.stockRating 具有stockRating
属性,为什么this.$refs.stockRating
未定义,而且我看到它也包含正确的元素? How do I resolve this?我该如何解决这个问题?
Well your $refs.stockRating is defined AND exists but it will not exists until the component is mounted as explained here .好吧,您的 $refs.stockRating 已定义并存在,但在按照此处说明安装组件之前,它不会存在。
I didn't try it but I guess that if you try to console.log
your $refs.stockRating
inside the mounted(){} component property it should not be empty我没试过,但我想如果你尝试在 mounted(){} 组件属性中
console.log
你的$refs.stockRating
它不应该是空的
You have to tell vue that DOM is ready and component was mounted.您必须告诉 vue DOM 已准备就绪并且组件已安装。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.