实例1
template
<ul>
<li
v-for="(item,index) in arr"
:key="item.name"
:class="{active:index === currentIndex}"
@click="liClick(index)"
>{{index+1}}.{{item.name}}</li>
</ul>
js
export default {
data() {
return {
arr: [
{
name: "shasha",
age: 27,
},
{
name: "he",
age: 29,
},
{
name: "hex",
age: 2,
},
],
currentIndex: 0,
};
},
methods: {
liClick(index) {
this.currentIndex = index;
},
},
};
style
<style scoped>
ul > li {
cursor: pointer;
}
.active {
color: red;
}
</style>
实例2
template
<template>
<div>
<h2>示例1</h2>
<ul>
//对象方式:class="{类名:布尔值}"
<li v-for="(po,index) in posts" :key="po.id" :class="{active:po.active}" @click="liClick(po,index)">{{po.title}}</li>
</ul>
</div>
</template>
js
data() {
return {
posts: [
{ id: 1, title: "My journey with Vue" ,active:false},
{ id: 2, title: "Blogging with Vue",active:false },
{ id: 3, title: "Why Vue is so fun" ,active:false},
],
};
},
//渲染前
create(){
},
//页面渲染后
mounted() {
this.posts[0].active = true;
},
methods:{
liClick(e,i){
this.posts.forEach((item,index)=>{
if(index != i)
item.active = false;
else
this.posts[i].active = true;
})
}
}
};
style
<style scoped>
.active {
color: red;
}
</style>