refs in Vue 3

When I migrated from Vue 2 to Vue 3, one thing was annoying - how to get access to a DOM element in Composition API? In Vue 2, it was easy, you just needed to use the this.$refs object. How to do it in Vue 3?

<script setup>
import { ref } from 'vue'

const inputText = ref()

const setFocus = () => {
    inputText.value.focus()
}
</script>

<template>
  <input type="text" ref="inputText"/>
  <button @click="setFocus()">set focus</button>
</template>

Ta-da! You only need to create a reactive variable in the script section - just remember that a name of a variable has to be like value in ref. You can see the working example here.

I'll create short posts like this from time to time. It's a small thing but it might be annoying while migrating to the new version of Vue.

Comments

Blog Comments powered by Disqus.

Older Post Newer Post