• Vue 点击 for 循环中的项会改变样式,循环的每一项互不影响


    话不多说,先上代码,以示敬意。

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Vue 点击 for 循环中的项会改变样式,循环的每一项互不影响</title>
            <style type="text/css">
                .list {
                    font-size: 15px;
                    line-height: 50px;
                    background-color: #00FFFF;
                    margin-bottom: 20px;
                    text-align: center;
                }
    
                .active {
                    font-size: 30px;
                }
            </style>
        </head>
        <body>
            <div id="app">
                <div class="list" :class=" arrActive.includes(index) ? 'active' : '' " v-for="(item, index) in list" :key="index" @click="listClick(index)">
                    {{item}}
                </div>
            </div>
    
            <script src="../vue.js"></script>
    
            <script>
                const app = new Vue({
                    el: '#app',
                    data: {
                        list: [1, 2, 3, 4, 5],
                        arrActive: []
                    },
                    methods: {
                        listClick(index) {
                            let hash = this.arrActive.findIndex(item => {
                                return item == index
                            })
                            if (hash > -1) {
                                this.arrActive.splice(hash, 1)
                            } else {
                                this.arrActive.push(index)
                            }
                        }
                    }
                })
            </script>
        </body>
    </html>

    原理:利用一个空数组,用来存储点击项的下标,通过控制数组来达到效果。

    主要运用到的是几个数组的方法。

    1. arrActive.findIndex() 找到的是数组里第一个的位置,找不到返回 -1。

    2. arrActive.includes() 判断是否包含某一元素,它直接返回 true 或者 false 表示是否包含元素。

    3. arrActive.splice(hash, 1) 从数组中第 hash 项删除 1 项,然后返回删除后的数组。

    4. arrActive.push(index) 如果点击的那一项,在数组 arrActive 中不存在,就把下标给添加到数组中。

  • 相关阅读:
    (Lineup the Dominoes筛子)三维状压
    Halloween Costumes 玄学题
    jQuery之动画
    javascript之位置
    javascript之事件
    jQuery之DOM
    jQuery之选择器
    jQuery简介
    javascript之Bom简介
    javascript之DOM操作
  • 原文地址:https://www.cnblogs.com/china825829/p/13071214.html
Copyright © 2020-2023  润新知