原理其实很简单,当currentIndex为0时,数组下标0的元素的active为true,其余的为false,所以为true的元素class会生效。
<body>
<div id="app">
<ul>
<li @click="liClick(index)"
:class="{active:currentIndex==index}"
v-for="(item,index) in list">{{item}}</li>
</ul>
</div>
<script src="./js/vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
list: ["西游记", "红楼梦", "三国演义", "水浒传"],
currentIndex: 0
},
methods: {
liClick(index) {
this.currentIndex=index
}
}
})
</script>
<style>
.active {
color: red;
}
</style>
</body>