Getting width of an image fails on first load in VUE3 #9338
-
Hello community, on the first load of a page i am getting the width of an image. At first it was collected like this: Then i tried using Vue's Template: JS: Test: Again the width value was 0 on the first load. When i triggered my resize function it fetched the width correctly. My guess is, that the template is rendered and the js code is triggered before the actual image has reached the client side. How do i get the width correctly on the first load? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Try import { nextTick, onMounted } from 'vue';
onMounted(() => {
nextTick(() => {
console.log(picture.value.getBoundingClientRect());
console.log(picture.value.clientWidth);
});
}); |
Beta Was this translation helpful? Give feedback.
-
Thank you for your help. In the meantime i tried a small timeout: Vue Template part <template>
<img id="bezel" src="/storage/assets/mockup.webp" alt="frame" ref="picture">
</template> JS in Vue import {nextTick, onMounted, ref} from "vue";
const picture = ref(null)
onMounted(() => {
setTimeout(init, 100);
function init() {
console.log(picture.value.getBoundingClientRect())
console.log(picture.value.clientWidth)
}
}) The timeout works fine but doesn't look like a clean solution for me. |
Beta Was this translation helpful? Give feedback.
-
You need to wait for the |
Beta Was this translation helpful? Give feedback.
You need to wait for the
load
event on your image element.