需求说明
比如:20个元素,3个显示红色文字,3个显示黑色文字,3个显示红色文字,3个显示黑色文字,以此类推
实现效果
方案一:纯css实现
<script setup lang="ts"></script>
<template>
<ul>
<template v-for="index of 20" :key="index">
<li>{{ index }}</li>
</template>
</ul>
</template>
<style scoped>
ul li:nth-of-type(6n + 1),
ul li:nth-of-type(6n + 2),
ul li:nth-of-type(6n + 3) {
color: red;
}
</style>
方案二: 结合js实现
<script setup lang="ts">
function needClsNew(index: number, num: number) {
const tmp = index % (2 * num)
return tmp >= 1 && tmp <= num
}
</script>
<template>
<ul>
<template v-for="index of 20" :key="index">
<li :class="needClsNew(index, 3) ? 'red' : ''">{{ index }}</li>
</template>
</ul>
</template>
<style scoped>
.red {
color: red;
}
</style>