在Vue的data中传入数组,然后在li标签中执行v-for循环,让他渲染在li标签里,然后,绑定点击函数,最后动态绑定。直接上代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.active {
color: #f00;
}
</style>
</head>
<body>
<div id="divId">
<ul>
<!-- 采用对象的思想 -->
<!-- <li v-for="(item,index) in movies" :key="index"
:class="{active:index===currentIndex}"
@click="change(index)">{{item}}</li> -->
<!-- 这里也可以采用三元表达式 -->
<!-- 采用v-for循环 -->
<li v-for="(item,index) in movies" :key="index"
:class="index===currentIndex?'active':''"
@click="change(index)">{{item}}</li> <!-- 点击的index是否等于当前的index值
,是就传true,执行class:active,不是则传false,执行为空 -->
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const vm = new Vue({
el: "#divId",
data: {
currentIndex: 0,
movies: ["海王", "海贼王", "火影忍者", "复仇者联盟"],
},
methods: {
change(index) {
this.currentIndex = index //注意this指向
},
},
computed: {
}
})
</script>
</body>
</html>