代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.active {
color:red;
}
</style>
</head>
<body>
<div id="app">
<h2 v-pre>vue小例子,遍历数组时,点击哪个哪个就变红</h2>
<ul>
<li v-for="item,index in names" @click="btn(index)" :class="{active:index==currentIndex}">{{item}}</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
names:['jack','james','jackson','java','javascript'],
currentIndex:-1
},
methods:{
//把点击的index传到这里来,再传给durrentIndex,然后再回到HTML中判断
btn(index){
this.currentIndex=index;
}
}
})
</script>
</body>
</html>
重点
1.@click="btn(index)"
在HTML中给v-on加个参数index,可以把v-for的index传到vue的methods里,这样methods就知道哪个index被点击了
2.this.currentIndex=index
在methods里把HTML中传进来的index再传给currentIndex,再回去HTML判断
运行效果
这效果应该很常用,写了几遍,算是背下来了,但还是不是很理解,继续再敲几遍,背熟了拉倒,我不懂,但是我会写