1. 程式人生 > 其它 >v-for迴圈出不同的背景色或圖片

v-for迴圈出不同的背景色或圖片

技術標籤:vue

使用場景

通常v-for迴圈出來的資料都是介面給到的,但是不會有iocn圖示,或者設計稿的不同背景色,因此返回資料不同就進行不同顏色或圖片變更。

思路

重點是通過v-bind進行繫結class,設定它的[index],在data裡面進行定義,樣式裡面進行引入需要的背景圖或者color樣式,如果是背景圖也同背景色寫法。

<div
        class="icon"
        :class="color[index]"
      ></div>
data(){
	return{
		color:
["colorOne", "colorTwo", "colorThere"], } }

全部程式碼

<template>
  <div class="demo">
    <div
      class="box"
      v-for="(item,index) in list"
      :key="index"
    >
      <div
        class="icon"
:class="color[index]" ></div> <div>{{item.name}}:{{item.age}}</div> </div> </div> </template> <script> export default { data() { return { color: ["colorOne", "colorTwo", "colorThere"
], list: [ { name: "小紅", age: "18" }, { name: "小白", age: "22" }, { name: "大胖", age: "31" }, ], }; }, }; </script> <style lang="scss" scoped> .demo { width: 500px; height: 200px; border: 1px solid red; display: flex; justify-content: space-around; .box { display: flex; .icon { width: 50px; height: 50px; } .colorOne { background: red; } .colorTwo { background: blue; } .colorThere { background: skyblue; } } } </style>

效果圖

在這裡插入圖片描述