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 中不存在,就把下標給添加到數組中。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM