Search code examples
javascriptvue.jsvuejs2ref

'this.$refs' is always empty in parent component


I'm trying to do a standard implementation of ref so that I can insert children elements into my InfoBox. But whatever I seem to put as a 'ref' element, never makes it to my InfoBox component. The result is always {} undefined from the log calls.

The click handler is to test timing issues, as using created vs mounted seemed to be a common issue.

<InfoBox
  v-if="waitingForCode">
  <p ref="infoboxcontent">A 7-digit verification code has been sent.</p>
</InfoBox>

and

<template>
  <div
    class="info-box"
    @click="clicked" >
    {{ this.$refs.infoboxcontent }}
  </div>
</template>

<script>
export default {
  name: 'InfoBox',
  mounted() {
    console.log(this.$refs, this.$refs.infoboxcontent)
  },
  methods: {
    clicked() {
      console.log(this.$refs, this.$refs.infoboxcontent)
    }
  }
}
</script>

<style scoped>
  // some style
</style>

I'm starting to think I fundamentally misunderstand the usage of the 'ref' attribute since this seems like a trivial example. Any help would be greatly appreciated.


Solution

  • The ref Vue special attribute is used to refer a DOM node (or a child component) from your current component template.

    If you want to pass some content to a custom component, this is the use case for a <slot> Vue built-in component.