Skip to content

Vue Composition API: Refs

Mike Lyttle edited this page May 9, 2023 · 1 revision

Class Component

    focusOnDate(date: DateWrapper): void {
        const dateEpoch = date.fromEpoch();
        const container = this.$refs[dateEpoch] as HTMLElement[];
        container[0].querySelector("button")?.focus();
    }
    <div
        v-for="dateGroup in dateGroups"
        :key="dateGroup.key"
        :ref="dateGroup.key"
    >
    </div>

Composition API

import { ref } from "vue";
const dateRefs = ref(new Map<string, HTMLElement>());
function focusOnDate(date: DateWrapper): void {
    const dateEpoch = date.fromEpoch();
    const container = dateRefs.get(dateEpoch);
    container?.querySelector("button")?.focus();
}
    <div
        v-for="dateGroup in dateGroups"
        :key="dateGroup.key"
        :ref="(el) => dateRefs.set(dateGroup.key, el)"
    >
    </div>

Notes

  • This is a complicated example where we are storing a collection of references that we want to index by a key. A Map wouldn't be needed in other instances.

Documentation

Clone this wiki locally