[Bug] Vue 中<img>标签 的:src 无法直接加载本地图片

991 阅读1分钟

1.问题

实现"点击按钮,切换图片"功能时.直接在<img>中写

 <img src="../../statics/1.png"  />

图片可以正确加载。

而改为 vue 的属性绑定时,图片加载失败:

<template>
 <div>
   <h1>在单组件中完成图片切换功能</h1>
   <img :src="imgSrc" alt="" />
   <button @click="changeImg">切换图片</button>
 </div>
</template>
<script>
export default {
 data() {
   return {
     urlList: [
       "../../statics/1.png",
       "../../statics/2.png",
       "../../statics/3.png",
     ],
     index: 0,
     imgSrc: "",
   };
 },
 methods: {
   changeImg() {
     this.index = (this.index + 1) % 3; //循环size = 3 的数组
      this.imgSrc = this.urlList[this.index] ;
   },
 },
};
</script>

浏览器控制台的报错为:

image.png

2.解决方案

方案1

在data()的return{}内的imgSrc属性使用require(),并将imgSrc绑定到<img>。 但只能加载一张图,灵活性很差。

<template> 
...
<img :src="imgSrc" alt="" /> 
...
</template>
<script>
...
  imgSrc: require("/statics/3.png"),
...
</script>

方案2 继续改造 imgSrc 将其改作一个数组

 <template>
...
    <img :src="imgSrc[index]" alt="" />
...
</template>
<script>
export default {
  data() {
    return {
      //urlList: ["/statics/1.png", "/statics/2.png", "/statics/3.png"],
      index: 0,
      imgSrc: [require("/statics/1.png"),require("/statics/2.png"),require("/statics/3.png")],
    };
  },
  methods: {
    changeImg() {
      this.index = (this.index + 1) % 3; //循环size = 3 的数组
    },
  },
 
};
</script>

问题解决。

3.拓展阅读

  1. vue中img的src动态赋值(本地图片的路径) - 简书 (jianshu.com)
  2. Vue中img的src属性绑定与static文件夹 - 简书 (jianshu.com)