Reputation: 1902
I'm trying to update an image dynamically but it is not updated.
According to the doc I have a template:
<template>
<section class="relative">
<div class="">
<img ref="heroImg" class="" src='../images/hero-bg-01.jpg' width="1440" height="577" />
</div>
</section>
</template>
Now I would like to update the src of my img and I do:
import { ref, onMounted } from "vue";
export default {
name: 'HeroTestimonials',
props:["source", "dataV"],
setup(){
const heroImg = ref(null);
onMounted(() => {
const imgUrl = new URL('../images/hero-bg-02.jpg', import.meta.url).href;
heroImg.src = imgUrl;
console.log(heroImg);
})
return {heroImg}
},
}
Into the console I have the message:
{ "_rawValue": null, "_shallow": false, "__v_isRef": true, "_value": null, "src": "http://localhost:3001/src/images/hero-bg-02.jpg" }
No errors but the image is not updated yet.
What's wrong?
Thanks for any suggestion!
[EDIT] - I've added the line return {heroImg} which was missing.
Upvotes: 0
Views: 1772
Reputation: 36
If you want to make the src attribute dynamic, you must use a v-bind in front of the attribute, for exemple v-bind:src="yourVariableHere" or use the shorthand :src. (you can see more here : https://v3.vuejs.org/api/directives.html#v-bind)
In your exemple you should do something like that :
<img class="" :src='imgUrl' width="1440" height="577" />
Then, in your script section :
<script>
import { onMounted, ref } from 'vue';
export default {
name: 'App',
setup() {
const imgUrl = ref('../images/hero-bg-01.jpg')
onMounted(() => {
imgUrl.value = '../images/hero-bg-02.jpg';
})
return {
imgUrl
}
}
}
</script>
However I'm not sure about doing that in the onMounted hook because the image would get replaced instantly
Upvotes: 1