I have a component layout like the following:
<div v-for="item in items" :key="item.id">
<div ></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:
- Grab the item from the list where item ID = X.
- Grab the ".sub-item" HTMLElement under the selected item to adjust the elements "style.width" dynamically.
Thanks in advance.
CodePudding user response:
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 :></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>