$refs empty in mounted callback when another component is a parent

Versions

  • nuxt: v2.15.1
  • node: v14.15.5

Reproduction

In the following sandbox, you can see that the alert shows undefined due to SectionTemplate element being the parent of the referenced div. If there is no component parent, it will correctly show the HTMLElement reference. Possibly a @nuxt/components v2 issue.

// SectionTemplate.vue

<template>
  <section>
    <slot />
  </section>
</template>
<template>
  <SectionTemplate>
    <div ref="div">test</div>
  </SectionTemplate>
</template>

<script>
export default {
  mounted() {
    alert(this.$refs.div);
  },
};
</script>

https://codesandbox.io/s/trusting-shadow-tvc8e?file=/pages/index.vue

Steps to reproduce

Make another Vue component a parent of your current component and $refs will be undefined. Worked as it should in 2.14 with @nuxt/components v1 (if it is relevant information).

What is Expected?

Element references should be ready in mounted callback as there is no asynchronous behavior.

What is actually happening?

Element references are not defined.

1 possible answer(s) on “$refs empty in mounted callback when another component is a parent

  1. @mystrdat Downgrading is not possible but you can force enable loader for development for 1.x behavior: (not recommanded nor guaranteed to always work)

    export default {
      components: {
        loader: true
      }
    }

    BTW regardless you should ensure rendering is done before accessing $refs as mentioned vue docs.