Vue 组件中 this.$refs 始终为空或未定义

bjo*_*and 6 javascript ref vue.js

我是 Vue 新手,正在尝试使用 $refs 从同级组件中获取 DOM 中的一些元素(出于非常基本的目的,只是为了获取它们的高度等),并且我是在计算中这样做的。

无论我尝试什么,this.$root.$refs要么总是以未定义的形式返回,要么作为空对象返回,而且我不知道我做错了什么。

在父组件中,我有:

<template>
<ComponentA />
<ComponentB />
</template>
Run Code Online (Sandbox Code Playgroud)

AI 组件中有:

<template>
  <div id="user-nav">
   <div ref="nav-container">
    <slot />
   </div>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

我只是尝试看看是否可以通过控制台日志记录在 ComponentB 中访问它

 console.log(this.$root.$refs);
Run Code Online (Sandbox Code Playgroud)

在该组件的安装函数中。

但我不断得到一个空物体。

你能不能像这样跨同级组件访问东西吗???

Lud*_*fyn 7

您可能已经解决了这个问题,但只是回答这个问题:

我遇到了类似的问题,似乎发生这种情况是因为在 Vue 有时间用自己的版本替换根 DOM 之前调用该函数。要解决此问题,您可以做的是创建一个mounted生命周期挂钩并在那里调用该函数。

const vm = new Vue({
  el: '#app',
  data: {
    sayHi: 'Hello World',
  },
  mounted: function() { // The hook. Here, Vue has already worked its magic.
    console.log('YOUR ELEMENT ----> ', this.doSomething())
  },
  methods: {
    doSomething: function() {
      return this.$refs['nav-container']
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <span ref="nav-container">{{ sayHi }}</span>
</div>
Run Code Online (Sandbox Code Playgroud)

我在这里找到了解决方案


Geo*_*rge 0

你可以做到,你遇到的问题是你的父组件实际上没有任何引用。

无论如何我不建议这样做,要么使用 vuex、eventbus 要么 $emit

Vue.component('componentA', {
  template: '<div><span ref="ref-inside-a">You\'re in A!</span></div>',
  methods:{
  log(){
  console.log('Hello from a')
  }
  }
})

Vue.component('componentB', {
  props: ['ball'],
  template: '<div><span>This is B!</span></div>',
  mounted() {
    this.$root.$refs['a'].log()    
    console.log(this.$root.$refs['a'].$refs['ref-inside-a'])
  }
})

new Vue({
  el: "#app",
  mounted() {
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <component-a ref="a"></component-a>
  <component-b ref="b"></component-b>

</div>
Run Code Online (Sandbox Code Playgroud)