vue3 update image src dynamically


I’m trying to update an image dynamically but it is not updated.

According to the doc I have a template:

   <section class="relative">
     <div class="">
        <img ref="heroImg" class="" src='../images/hero-bg-01.jpg' width="1440" height="577" />

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"],
      const heroImg = ref(null);

      onMounted(() => {
          const imgUrl = new URL('../images/hero-bg-02.jpg', import.meta.url).href;
          heroImg.src = imgUrl;
      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&quot; }

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.

>Solution :

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 :

In your exemple you should do something like that :

<img ref="heroImg" class="" :src='heroImg' width="1440" height="577" />

Then, in your script section :

    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 {

However I’m not sure about doing that in the onMounted hook because the image would get replaced instantly

Leave a ReplyCancel reply