Vue动态实现评分效果
1.图片分为三种
on:half: off
1 <style> 2 .star{ 3 font-size: 0; 4 } 5 .star-item{ 6 display: inline-block; 7 background-repeat: no-repeat; 8 width: 20px; 9 height: 20px; 10 margin-right: 22px; 11 background-size: 100%; 12 } 13 .star-item.on{ 14 background-image: url(img/on.png); 15 } 16 .star-item.half{ 17 background-image: url(img/half.png); 18 } 19 .star-item.off{ 20 background-image: url(img/off.png); 21 } 22 </style>
1 <div id="app"> 2 <ul class="star"> 3 <span v-for="(itemClass,index) in itemClasses" :class="itemClass" class="star-item" track-by="index"></span><!--性能优化 track-by 数据不改变时不会重新渲染--> 4 </ul> 5 </div>
1 <script> 2 new Vue({ 3 el: '#app', 4 data:{ 5 score: 4 6 }, 7 computed:{ //计算属性 8 itemClasses(){ 9 let result = []; 10 let score = Math.floor(this.score * 2 ) / 2; 11 let hasDecimal = score % 1 !== 0; 12 let integer = Math.floor(score); 13 for(let i=0;i<integer;i++){ 14 result.push("on"); 15 } 16 if(hasDecimal){ 17 result.push("half"); 18 } 19 while(result.length < 5){ 20 result.push("off"); 21 } 22 return result; 23 } 24 } 25 }) 26 </script>
根据需求改变代码