无法使用 Vue.js 中的 this.$refs 访问单个元素
Cannot access individual elements with this.$refs in Vue.js
我有一个奇怪的问题。想访问 created() 钩子中的一些元素。具体来说:
我可以访问 refs 对象:
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
挂钩访问引用,因为子 components/elements 尚未实例化;而是从 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
输出显示组件存在但当您访问其中一个组件时出现差异的原因可能是浏览器正在评估 this.$refs
仅在您单击箭头展开对象的属性时延迟执行,并且在评估时已创建子组件。
this.$refs
是一个object类型,当你的output被创建的时候,它会得到一个undefined的值,然后它会在mounted中得到另一个object类型的值,并且这两个值在内存中有相同的引用,要么改变,另一个就会改变。
我有一个奇怪的问题。想访问 created() 钩子中的一些元素。具体来说: 我可以访问 refs 对象:
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
挂钩访问引用,因为子 components/elements 尚未实例化;而是从 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
输出显示组件存在但当您访问其中一个组件时出现差异的原因可能是浏览器正在评估 this.$refs
仅在您单击箭头展开对象的属性时延迟执行,并且在评估时已创建子组件。
this.$refs
是一个object类型,当你的output被创建的时候,它会得到一个undefined的值,然后它会在mounted中得到另一个object类型的值,并且这两个值在内存中有相同的引用,要么改变,另一个就会改变。