Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

<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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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&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 : https://v3.vuejs.org/api/directives.html#v-bind)

In your exemple you should do something like that :

<img ref="heroImg" class="" :src='heroImg' 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading