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>
posted @ 2021-03-29 14:09  bugSource  阅读(1108)  评论(0编辑  收藏  举报