VueJS3 - Get handle to element within for loop

Viewed 27

I have a component layout like the following:

<div class="list-item" v-for="item in items" :key="item.id">
  <div class="sub-item"></div>
</div>

The problem I'm having is, how do I grab the handle of that sub-item element on demand? I need to essentially do something like this:

  1. Grab the item from the list where item ID = X.
  2. Grab the ".sub-item" HTMLElement under the selected item to adjust the elements "style.width" dynamically.

Thanks in advance.

1 Answers

To change the element with certain id in your for loop you can use a condition inside your v-for like this:

<div id="container" v-for="item in items" :key="item.id">
  <div :class="item.id == ID ? 'sub-item change-width-class' : 'sub-item'"></div>
</div>

You can listen the timer and change the currentElement by id using a watcher:

<template>
    <div id="container" v-for="item in items" :key="item.id">
        <div :id="`sub-item-${currentElementId}`></div>
    </div>
</template>

<script setup>
    import { ref, watch } from 'vue';

    const timer = ref(0);
    const currentElementId = ref(1);

    // every time timer updates the function below will run
    watch(timer, () => {
        const subItem = document.querySelector(`.sub-item-${currentElementId}`);
        subItem.style.width = (100 * timer / 250); 
    });

</script>
Related