问题描述
通过
v-for指令,按照index动态生成class
例如: .item-1 .item-2 .item-3 .item-4 .item-5 其中,1,2,3,4,5为循环遍历的下标。
实现原理
通过methods将index传入,并自定义返回值类型。
注意: 此处无法使用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>
本文详细介绍如何在Vue.js中利用v-for指令结合自定义方法generateClassName,动态生成带有循环下标作为后缀的class名,如game_item-1、game_item-2等。这种方法在创建多个具有相似样式但需区分的元素时非常实用。
7120

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



