gpt4 book ai didi

javascript - 无法使用 this.$refs 在 Vue.js 中访问单个元素

转载 作者:行者123 更新时间:2023-11-30 13:50:15 28 4
gpt4 key购买 nike

我有一个奇怪的问题。想访问 created() 钩子(Hook)中的一些元素。具体来说:我可以访问 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 钩子(Hook)访问 refs,因为子组件/元素还没有被实例化;而是从 mounted Hook 访问:

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 只有在您单击箭头以展开对象的属性时才延迟执行,并且在对它求值时子组件已创建。

关于javascript - 无法使用 this.$refs 在 Vue.js 中访问单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405856/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com