前段时间做页面时需要动态设置背景图片,每一种框架都会遇见类似的需求,特记录下来,以免不时之需:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> li span { width: 100px; height: 100px; border-radius: 999px; border: 1px solid red; background-position: center center; -webkit-background-size: cover; background-size: cover; display: inline-block; } </style> </head> <body> <ul id="app"> <li v-for= "item in a"> <span :style="{backgroundImage: ‘url(‘ +item.b+ ‘)‘}">111</span> </li> </ul> </body> <script src="js/vue.js"></script> <script> var a= new Vue({ el: "#app", data: { a: [{b: ‘./img/gintama.jpg‘}, {b: ‘./img/glass.jpg‘}, {b: ‘./img/leader.jpg‘}] } }) </script> </html>
核心代码:
<li v-for= "item in a">
<span :style="{backgroundImage: ‘url(‘ +item.b+ ‘)‘}">111</span>
</li>
分析:
:style为字符串类型的对象,在对象内,属性名简写,属性值为字符串类型,即必须带上‘,
而根据vue的语法,使用vue值的时候不需要像angular一样用{{}}包裹