1.服务端返回图片链接
<div
class="bg-img"
:style="{ backgroundImage: `url(${imgUrl})` }" />
2.引用本地的图片
<div
class="bg-img"
:style="{ backgroundImage: `url(${imgUrl})` }" />
imgUrl: require('../assets/bg-img.png'),
一定要以require的方式引入,否则项目编译完渲染的时候路径有问题。
3.v-for 循环出来的 div 设置不同的背景
- 动态绑定类名
<div v-for="(item, index) in list" :key="index" class="list-item"> <div class="item-title" :class="bgImg[index]" /> </div>
- 定义类名映射数组
data() { return { bgImg: ['bg-img0', 'bg-img1', 'bg-img2'], }; },
- 在style中设置背景图
.bg-img0 { background: url(../assets/images/title0.png) center no-repeat; } .bg-img1 { background: url(../assets/images/title1.png) center no-repeat; } .bg-img2 { background: url(../assets/images/title2.png) center no-repeat; }
原文链接:https://blog.csdn.net/xh17864388739/article/details/122475500