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

问题描述 投票:0回答:1

我有一个奇怪的问题。想要访问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)

javascript vue.js this refs
1个回答
0
投票

您无法从created挂钩访问引用,因为子组件/元素尚未实例化;而是从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的属性单击箭头以展开对象的属性,并在评估该对象时已创建子组件。

© www.soinside.com 2019 - 2024. All rights reserved.