How to get <script setup> style component's Ref

normalChild.vue

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup() {
    const name = ref('normal-child')
    function nameChange() {
      name.value += '-change'
    }
    return { name, nameChange }
  }
})
</script>

sugarChild.vue

<script setup lang="ts">
ref: name = 'sugar-child'
function nameChange() {
  name += '-change'
}
</script>

index.vue

<template>
  <NormalChild ref="NormalChildRef" />
  <SugarChild ref="SugarChildRef" />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import NormalChild from './normalChild.vue'
import SugarChild from './sugarChild.vue'

// const NormalChildRef = ref(null)
ref: NormalChildRef = null

const SugarChildRef = ref(null)
// ref: SugarChildRef = null

onMounted(() => {
  console.log('NormalChildRef', NormalChildRef)  // => child-ref
  console.log('SugarChildRef', SugarChildRef)  // => {}  a empty object
})
</script>

if child-component is a style component,ref(null) can’t get Refs

Did you find a solution?

I can’t remember where I found this in the vue documentation, but the answer would be:

const NormalChildRef = ref<InstanceType<typeof NormalChild>>()
const SugarChildRef = ref<InstanceType<typeof SugarChild>>()

The key is that the const name MUST match the ref= in the element.

1 Like

Replying to my own post. The documentation link I couldn’t remember was: https://v3.vuejs.org/guide/typescript-support.html#typing-template-refs

1 Like