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

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

作者: 满船清梦压星河ya_ | 来源:发表于2020-07-19 11:45 被阅读0次

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

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <style>
      .active{
        color: red;
      }
    </style>
    
      <!-- 作业需求:点击列表中的哪一项,那么该项的文字变成红色 -->
    <div id="app">
        <ul>
            <li v-for="(item, index) in movices" :class="{active:index==mark}" @click="getcolor(index)">{{ index }}-{{ item }}</li>
        </ul>
    </div>
    
    <script src="../js/vue.js"></script>
    <script>
      const app = new Vue({
        el: "#app",
        data: {
          mark : -1,
          movices: ['复仇者联盟','钢铁侠','美国队长','小黑历险记']
        },
        methods: {
          getcolor: function(index) {
            if(index == this.mark){
              this.mark = -1 // if判断,实现点击一项时变色,再次点击,取消变色
            }else{
              this.mark = index
            }
            
          }
        }
      })
    </script>
    </body>
    </html>
    

    v-for="(item, index) in movices"循环展示列表的同时,取列表的下标index。

    :class v-bind 的语法糖,动态绑定class。

    相关文章

      网友评论

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

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