vue 使用v-for 动态修改class

本文详细介绍如何在Vue.js中利用v-for指令结合自定义方法generateClassName,动态生成带有循环下标作为后缀的class名,如game_item-1、game_item-2等。这种方法在创建多个具有相似样式但需区分的元素时非常实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

通过v-for指令,按照index动态生成class

例如: .item-1 .item-2 .item-3 .item-4 .item-5 其中,1,2,3,4,5为循环遍历的下标。

实现原理

通过methodsindex传入,并自定义返回值类型。

注意: 此处无法使用computed实现!!!

原因是computed是无法获取到当前遍历的index值,可以自己动手试一试。

源码实现

<template>
  <div class="game">
    <div class="game_item" v-for="(item,index) in gameList" :class="generateClassName(index)" :key="index">
        {{item}}
    </div>
  </div>
</template>

<script>
export default {
  name: 'game',
  data () {
    return {
      gameList: Array(40).fill(1)
    }
  },
  methods: {
    generateClassName (index) {
      // 调用方法,动态生成index
      return `game_item-${index}`
    }
  }
}
</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值