The problem that Vue dynamically sets the src of img does not take effect

Cause Analysis

Sometimes in the VUE project, it is necessary to dynamically modify the src of Img. If you modify it directly, the image will not be displayed.
This is because src is treated as a static resource and has not been compiled.

<template>
    <div class="first">
      <!-- 普通加载 (不显示)出错-->
     <el-carousel height="280px">
          <el-carousel-item v-for="(item,index) in banners" :key="index">
            <img :src="item" alt="">
          </el-carousel-item>
        </el-carousel>
    </div>
</template>
<script>
export default {
    
    
  // 定义数据
    data(){
    
    
        return {
    
    
            banners:["./2.jpeg","./3.jpeg"],
          }
    },
}
</script>
 

insert image description here

Solution

The first one uses require to introduce pictures

<template>
     <el-carousel height="280px">
          <el-carousel-item v-for="(item,index) in banners" :key="index">
            <img :src="item" alt="">
          </el-carousel-item>
        </el-carousel>
</template>
<script>
export default {
    
    
  // 定义数据
    data(){
    
    
        return {
    
    
              banners: [require('../../assets/images/banner1.jpg'), require('../../assets/images/banner2.jpg'), require('../../assets/images/banner3.jpg')]
          }
    },
}
</script>

The second is to import the picture into the file first

<template>
    <el-carousel height="280px">
          <el-carousel-item v-for="(item,index) in banners" :key="index">
            <img :src="item" alt="">
          </el-carousel-item>
        </el-carousel>
    </div>
     
</template>
<script>
import img1 from "../../assets/images/banner1.jpg"
import img2 from "../../assets/images/banner2.jpg"
import img3 from "../../assets/images/banner3.jpg"
export default {
    
    
  // 定义数据
    data(){
    
    
        return {
    
    
              banners:[img1,img2,img3]
          }
    },
}
</script>

The third way is to put the picture into the public folder of the vue project and call it in the root directory

<template>
     <el-carousel height="280px">
          <el-carousel-item v-for="(item,index) in banners" :key="index">
            <img :src="item" alt="">
          </el-carousel-item>
        </el-carousel>
</template>
<script>
export default {
    
    
  // 定义数据
    data(){
    
    
        return {
    
    
              banners: ['/banner1.jpg','/banner2.jpg','/banner3.jpg']
          }
    },
}
</script>

achieve effect

insert image description here

Guess you like

Origin blog.csdn.net/qq_46258819/article/details/126989076