v-for动态图片列表以及动态给div添加背景图片方法
效果如下图所示:
HTML:
<div class="branchWorkshop">
<ul>
<li v-for="(item,i) in workShopList" :key="i">
<div class="workshopImg"
:style="{ 'background-image': 'url(' + item.imgUrl + ')',
'background-repeat':'no-repeat','background-size':'cover'}">
</div>
<span style="color:white">{{item.label}}</span>
</li>
</ul>
</div>
JS:
<script>
export default {
data(){
return{
workShopList:[{
id: 1
imgUrl: "/static/manyou/ws.png"
label: "demo"
},{
id: 2
imgUrl: "/static/manyou/zz.png"
label: "demo"
},{
id: 3
imgUrl: "/static/manyou/ym.png"
label: "demo"
},{
id: 4
imgUrl: "/static/manyou/zxn.png"
label: "demo"
},{
d: 5
imgUrl: "/static/manyou/ns.png"
label: "demo"
},
{
d: 6
imgUrl: "/static/manyou/wm.png"
label: "demo"
}
]
}
}
}
</script>
CSS:
<style>
.branchWorkshop{
width: 400px;
height: 650px;
overflow: hidden;
}
.branchWorkshop ul{
display: flex;
width: 90%;
height: 100%;
margin:0;
padding:0;
flex-wrap: wrap;
/* 垂直居中 */
align-items: center;
/* ul里面的字体图片水平居中 */
text-align:center;
/* ul盒子里面的内容水平居中 */
margin:0 auto;
}
.branchWorkshop li{
width: 30%;
height: 15%;
list-style: none;
/* li在ul里面水平居中 */
margin:0 auto;
margin-right: 2%;
}
.workshopImg{
width: 100%;
height: 100%;
}
</style>
总结:
动态给元素添加背景图片的方法:
<div class="workshopImg"
:style="{ 'background-image': 'url(' + item.imgUrl + ')',
'background-repeat':'no-repeat','background-size':'cover'}">
</div>