How to get ref of an element behind v-if #6127
-
<script setup>
import { onMounted } from "vue";
const div$ = ref();
const flag$ = ref(false);
onMounted(() => {
setTimeout(() => {
flag$.value = true;
}, 1000);
setTimeout(() => {
console.log(`ref: ${div$.value}`); // this will be undefined
}, 2000);
});
</script>
<template>
<div>
<div v-if="flag$"></div>
</div>
</template> |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You can use like this Example, Hope this helps you. <script setup>
import { onMounted, ref } from "vue";
const div$ = ref();
const flag$ = ref(false);
onMounted(() => {
setTimeout(() => {
flag$.value = true;
}, 1000);
setTimeout(() => {
console.log(`ref: `, div$.value); // this will be undefined
}, 2000);
});
</script>
<template>
<div>
<div ref="div$" v-if="flag$">Hello</div>
</div>
</template> new.mp4 |
Beta Was this translation helpful? Give feedback.
-
I think the current answer assumes a too simple scenario and relies on a seemingly arbitrary timeout. Let's assume that the v-if condition becomes true by some external action, and I need to perform an operation on the element behind the v-if immediately after it becomes visible. How can I achieve that? So far the only really working idea I have found is to turn the v-iffed element into its own single file component (SFC) and perform the required operations in an onMounted-function of that SFC. I have verified that this works as intended, but it seems a bit stupid. Is there no better way? |
Beta Was this translation helpful? Give feedback.
You can use like this Example, Hope this helps you.
new.mp4