看Vue学习视频中看到这个小练习,如title。实现如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homework</title>
<style>
.showRed{
color: red;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li v-for="(f, index) in fruits" :class="{showRed:isRed[index]}" @click="changColor(index)">{{f}}</li>
</ul>
</div>
<script src="https://vuejs.org/js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
fruits: ['Apple', 'Banana', 'Watermelon', 'Peach'],
isRed: Array(4).fill(false) // 这里数组长度写死了我认为是不好的地方,后续如果有更好的方法一定改进
},
methods: {
changColor(index) {
// 这里用到了map函数,感觉比较适合这里使用
this.isRed = this.isRed.map((v, i) => i == index);
}
}
});
</script>
</body>
</html>
未完待续...
更新,下面这种currentIndex方法更好,我之前的弄复杂了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homework</title>
<style>
.showRed {
color: red;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li v-for="(f, index) in fruits" :class="{showRed: currentIndex === index}" @click="changColor(index)">{{f}}
</li>
</ul>
</div>
<script src="https://vuejs.org/js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
fruits: ['Apple', 'Banana', 'Watermelon', 'Peach'],
currentIndex: -1
},
methods: {
changColor(index) {
this.currentIndex = index;
}
},
})
</script>
</body>
</html>