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