Blog>
Snippets

Dynamic Refs with v-for

Illustrate the creation of dynamic refs within a `v-for` loop and how to access these refs in the JavaScript code to perform operations on a list of elements.
new Vue({
    el: '#app',
    data: {
        items: [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, ...] // A list of items
    },
    methods: {
        // Method to access a specific item's ref
        accessRefById(id) {
            // We use this.$refs and the dynamic ref name to access the element
            const refName = `item-${id}`;
            const element = this.$refs[refName];
            console.log(element); // Perform operations with the element
        }
    }
});
This code defines a new Vue instance with a data property 'items' that holds an array of objects. Each object represents an item with an 'id' and 'name'. The 'accessRefById' method allows us to access a DOM element by its dynamically assigned ref.
<template>
    <div id="app">
        <div v-for="item in items" :key="item.id" :ref="`item-${item.id}`">
            {{ item.name }}
        </div>
    </div>
</template>
This part of the code is a template that uses the v-for directive to render a list of items. It dynamically assigns a ref to each item using the item's id which allows us to reference each element uniquely in our methods.