美文网首页
vue实现点击列表中的哪一项,哪一项就变颜色

vue实现点击列表中的哪一项,哪一项就变颜色

作者: 小圆圈Belen | 来源:发表于2022-02-16 10:32 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-bind</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
  <style>
    .changeColor {
      color: #42b983;
    }
  </style>
</head>

<!--需求描述:点击列表中的哪一项,那么该项的文字就变色-->
<body>
<div id= 'vue' >
  <h3>
    <ul>
      <li v-for="(famous, index) in stars" v-bind:class="{changeColor:index==currentIndex}" v-on:click=btnClick(index)>{{index}}-{{famous}}</li>
    </ul>
  </h3>
</div>
<script>
  let vm = new Vue({
    el: '#vue',
    data:{
      currentIndex :0,   
      stars: ['Lee', 'Leo', 'Lili', 'Alex'],
    },
    methods:{
      btnClick: function (index){
        this.currentIndex = index     //使currentIndex=index,这样就可以控制哪一个变色,相当于和class绑定
      }
    },
  })
</script>
</body>
</html>

相关文章

网友评论

      本文标题:vue实现点击列表中的哪一项,哪一项就变颜色

      本文链接:https://www.haomeiwen.com/subject/cugrlrtx.html