1.服务端返回图片链接

<div
  class="bg-img"
  :style="{ backgroundImage: `url(${imgUrl})` }" />
<div

2.引用本地的图片

<div
  class="bg-img"
  :style="{ backgroundImage: `url(${imgUrl})` }" />
<div
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;
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐