Vue小案例總結
需求:點擊哪個電影就讓其變紅
關鍵點是在data裏定義一個currentIndex來記錄當前被點擊電影的索引值,因爲我們需要依據這個索引獲取到當前被點擊的元素並修改顏色。
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.active{
color: red;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in movies" :class="{active:currentIndex===index}" @click="btnClick(index)">{{index}}----{{item}}</li>
</ul>
</div>
<script src="./js/vue.js"></script>
<script>
const vm = new Vue({
el:'#app',
data:{
movies:['雲圖','寄生蟲','盜夢空間','阿凡達'],
currentIndex:0,
},
methods:{
btnClick(index){
this.currentIndex=index
}
}
})
</script>
</body>
</html>
chrome展示結果如下: