Vue之點擊更換CSS樣式


GitHub項目Demo地址:https://github.com/Beingyo/vue-test-template/tree/main/src/page/clickChangeStyle

示例:

思路:通過點擊事件把對應的index賦值給nowIndex,通過:class把nowIndex = index時把原本的css樣式(normal-class)改為需要更換的css樣式(active-class)

說明::class="{ 'active-class': nowIndex === index }",當nowIndex = index時,該元素的class為active-class

代碼:

<template>
    <ul>
        <li
            v-for="(item,index) in list"
            :key="index"
            class="normal-class"
            :class="{ 'active-class': nowIndex === index }"
            @click="changeClass(index)"
        >
            點我
        </li>
    </ul>
</template>
<script>
    export default {
        name: 'clickChangeStyle',
        data () {
            return {
                list:[1, 2, 3, 4, 5],
                nowIndex: 0
            }
        },
        methods: {
            changeClass (index) {
                this.nowIndex = index
            }
        }
    }
</script>
<style scoped>
    .normal-class{
        display: inline-block;
        width: 30px;
        margin: 10px;
        background: lightgray;
    }
    .active-class{
        background: darkgray;
    }
</style>


免責聲明!

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



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