需求:1和2 背景颜色灰色
3和4 背景颜色白色
5和6 背景颜色灰色
7和8 背景颜色白色
开干
<template>
<div class="father">
<div
class="items"
v-for="(item, index) in datas"
:key="index"
:class="item.style == 'gray' ? 'gray' : 'white'"
>
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
datas: [
{ title: "品牌", type: "福田" },
{ title: "厂家", type: "汽车" },
{ title: "车系", type: "大进军" },
{ title: "车型名称", type: "个大概多少富豪的附属国豆腐干" },
{ title: "厂商指导价", type: "100万" },
{ title: "上市时间", type: "34534534" },
],
};
},
mounted() {
this.setAtrr();
},
methods: {
setAtrr() {
let count = false;
this.datas.forEach((element, index) => {
if ((index + 1) % 2) {
// 为基数
if (!count) {
this.$set(element, "style", "gray");
} else {
this.$set(element, "style", "white");
}
} else {
if (!count) {
this.$set(element, "style", "gray");
} else {
this.$set(element, "style", "white");
}
// 为偶数
count = !count;
}
});
console.log(this.datas);
},
},
};
</script>
<style scoped lang="less">
.father {
width: 200px;
height: 600px;
// background: rgb(231, 231, 231);
}
.items {
float: left;
width: 50%;
height: 60px;
border: 1px solid #334;
}
.gray {
background: rgb(173, 173, 173);
}
.white {
background: rgb(249, 253, 9);
}
</style>
该博客介绍了一个Vue.js组件中使用v-for进行数据循环,并根据奇偶性改变背景颜色的方法。通过设置items类的样式,实现了灰色和白色的交替显示。在mounted生命周期钩子中,使用this.$set动态添加style属性,确保了每个元素的背景颜色正确展示。
754

被折叠的 条评论
为什么被折叠?



