vue3动态更新图片src

vue3 update image src dynamically

我正在尝试动态更新图像,但它没有更新。

根据doc我有一个模板:

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

现在我想更新我的 img 的 src,我这样做了:

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}
   },
}

进入控制台我得到消息:

{ "_rawValue": null, "_shallow": false, "__v_isRef": true, "_value": null, "src": "http://localhost:3001/src/images/hero-bg-02.jpg" }

没有错误,但图像尚未更新。

怎么了?

感谢任何建议!

[编辑] - 我添加了 return {heroImg} 这行缺失的内容。

如果要使 src 属性动态化,必须在属性前面使用 v-bind,例如 v-bind:src="yourVariableHere" 或使用 shorthand :src。 (你可以在这里看到更多:https://v3.vuejs.org/api/directives.html#v-bind

在您的示例中,您应该这样做:

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

然后,在您的脚本部分:

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

但是我不确定是否要在 onMounted 挂钩中执行此操作,因为图像会立即被替换