前提:
有一个列表,使用 v-for 循环出来,点击哪一项,哪一项文字变色,这个功能很好实现,写好 active 类之后,在 html 中直接绑定即可,例如:
html:
<ul>
<li v-for="(item, index) in list"
:class="{'active': index === nowIndex}"
@click="selectOne(index)">
{{ item.name }}
</li>
</ul>
js:
selectOne (index) {
this.nowIndex = index
}
css:
.active {
color: '#428bca';
}
但是现在问题是,这个色值是服务器传过来的值,所以只能用如下方法:
html:
<div>
<ul>
<li v-for="(item, index) in list" :key="item.id" @click="selectOne(index)">
<span v-if="index === nowIndex" :style="{color: themeColor}">{{ item.name }}</span>
<span v-else>{{ item.name }}</span>
</li>
</ul>
</div>
js:
data () {
return {
themeColor: '#428bca',
nowIndex: 0,
list: [
{id: 1, name: 'apple'},
{id: 2, name: 'banana'},
{id: 3, name: 'orange'}
]
}
},
methods: {
selectOne (index) {
this.nowIndex = index
}
}
不知道有没有更加简单的写法或者其他的写法可以实现呢?