You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3使用ref动态更新img标签src属性不生效问题排查求助

问题根因

你直接给ref对象本身添加了src属性,没有访问ref对象持有的真实DOM元素:Vue3中所有通过ref()函数创建的响应式引用,要访问其实际存储的值(此处为img DOM节点),必须通过.value属性读取/修改。
从你打印的内容也能验证:heroImg是一个带有__v_isRef标识的ref包装对象,你赋值的src是挂载在这个包装对象上的自定义属性,和真实DOM完全无关,自然不会触发页面更新。

修正方案

方案1:修改DOM操作写法

仅调整onMounted内的赋值逻辑,通过.value获取真实DOM节点后再修改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.value.src = imgUrl;
      })
      return {heroImg}
   },
}

方案2:响应式绑定写法(更符合Vue设计规范,推荐)

不需要手动操作DOM,直接用响应式变量绑定img的src属性即可:
首先修改模板,把静态src改为动态绑定:

<template>
   <section class="relative">
     <div class="">
        <img class="" :src="heroImgUrl" width="1440" height="577" />
    </div>
  </section>
</template>

逻辑代码调整为声明响应式变量控制src:

import {  ref, onMounted } from "vue";
export default {
   name: 'HeroTestimonials',
   props:["source", "dataV"],
   setup(){
      const heroImgUrl = ref(new URL('../images/hero-bg-01.jpg', import.meta.url).href);

      onMounted(() => {
          const imgUrl = new URL('../images/hero-bg-02.jpg', import.meta.url).href;
          heroImgUrl.value = imgUrl;
      })
      return {heroImgUrl}
   },
}

内容的提问来源于stack exchange,提问作者Uncoke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:03