[英]Cannot access individual elements with this.$refs in Vue.js
我有一个奇怪的问题。 想要访问 created() 钩子中的一些元素。 具体来说:我可以访问参考文献 object:
created() { console.log(this.$refs) } // returns: { bar: div.red.bar content: div.name-description description: p.description.dark redContainer: div.red.red-container sections: div.sections title: h1.name.dark __proto__: Object }
但是,当我尝试针对特定元素时,我最终会得到未定义:
created() { console.log(this.$refs.content) } //returns undefined
有人知道我为什么会有这种行为吗? 尝试从计算属性中的元素获取宽度/高度时出现类似问题...(例如 this.$refs.content.clientWidth)
您无法从created
钩子访问 refs,因为子组件/元素尚未实例化; 而是从mounted
的钩子访问:
Vue.component('foo', { template: '<div>foo</div>', created() { console.log('foo created') } }) new Vue({ el: '#app', created() { console.log('parent created: $refs.foo is null?', this.$refs.foo == null) }, mounted() { console.log('parent mounted: $refs.foo is null?', this.$refs.foo == null) }, })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <foo ref="foo"></foo> </div>
您在console.log
output 之间出现差异的原因表明组件存在,但是当您访问其中一个组件时它不是可能是因为浏览器正在评估this.$refs
的属性,只有在您单击时才会懒惰箭头展开 object 的属性,在评估时,子组件已创建。
this.$refs is an object type,when you output in created,it will get a value undefined,then it will get another value of object type in mounted,and both value have a same reference in memory,either changed,another will change .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.