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

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


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


在父组件中,我有:


<template>

<ComponentA />

<ComponentB />

</template>

在组件 AI 中有:


<template>

  <div id="user-nav">

   <div ref="nav-container">

    <slot />

   </div>

  </div>

</template>

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


 console.log(this.$root.$refs);

在该组件的已安装功能中。


但我不断得到一个空对象。


你能不能像这样跨兄弟组件访问东西???


慕妹3146593
浏览 712回答 3
3回答

元芳怎么了

您可能已经解决了这个问题,但只是为了回答这个问题:我遇到了类似的问题,这似乎是因为在 Vue 有时间用自己的版本替换根 DOM 之前调用了该函数。你可以做些什么来解决这个问题是创建一个mounted生命周期钩子并在那里调用函数。const vm = new Vue({&nbsp; el: '#app',&nbsp; data: {&nbsp; &nbsp; sayHi: 'Ello World',&nbsp; },&nbsp; mounted: function() { // The hook. Here, Vue has already worked its magic.&nbsp; &nbsp; console.log('YOUR ELEMENT ----> ', this.doSomething())&nbsp; },&nbsp; methods: {&nbsp; &nbsp; doSomething: function() {&nbsp; &nbsp; &nbsp; return this.$refs['nav-container']&nbsp; &nbsp; }&nbsp; }})<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app">&nbsp; <span ref="nav-container">{{ sayHi }}</span></div>

白衣非少年

这可能不是您特定问题的答案,但我发现另一个$refs空的原因是定义它的组件尚未创建/安装。可能是由于 Vue 使用的延迟渲染。我有一组选项卡,其中一个是我有一个“ref=”的选项卡,如果我没有访问该选项卡,那么它$refs是空的。但是如果我第一次访问该选项卡,那么 ref 设置正确。

小唯快跑啊

你可以做到,你遇到的问题是你的父组件实际上没有任何参考。我不建议这样做,无论是使用 vuex、eventbus 还是 $emitVue.component('componentA', {&nbsp; template: '<div><span ref="ref-inside-a">You\'re in A!</span></div>',&nbsp; methods:{&nbsp; log(){&nbsp; console.log('Hello from a')&nbsp; }&nbsp; }})Vue.component('componentB', {&nbsp; props: ['ball'],&nbsp; template: '<div><span>This is B!</span></div>',&nbsp; mounted() {&nbsp; &nbsp; this.$root.$refs['a'].log()&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; console.log(this.$root.$refs['a'].$refs['ref-inside-a'])&nbsp; }})new Vue({&nbsp; el: "#app",&nbsp; mounted() {&nbsp; }})<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app">&nbsp; <component-a ref="a"></component-a>&nbsp; <component-b ref="b"></component-b></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript