Vue 类与样式

数据绑定的一个常见需求场景是操纵元素的 CSS class 列表和内联样式。因为 class 和 style 都是 attribute,我们可以和其他 attribute 一样使用 v-bind 将它们和动态的字符串绑定。但是,在处理比较复杂的绑定时,通过拼接生成字符串是麻烦且易出错的。因此,Vue 专门为 class 和 style 的 v-bind 用法提供了特殊的功能增强。除了字符串外,表达式的值也可以是对象或数组。

一、绑定Class

    <div class="item" :class="{ active: activeIndex == index }" v-for="(item, index) in students" @click="itemClick(index)">
        学生编号:{{ item.id }}
        学生姓名:{{ item.name }}
    </div>

css

<style>
.item {
    background-color: rgb(180, 180, 180);
    padding: 20px;
    border-bottom: 1px solid red;
    transition: all ease 1s;
}

.item.active {
    background-color: red;
    color: white;
    font-size: 20px;
}
</style>

js

<script>
export default {
    data() {
        return {
            students: [
                { id: 1, name: '张三' },
                { id: 2, name: '李四' },
                { id: 3, name: '王五' },
                { id: 4, name: '赵六' },
            ],
            activeIndex: -1
        }
    },
    methods: {
        itemClick(e) {
            console.info(e);

            this.activeIndex = e;
        }
    }
}
</script>

二、绑定内联样式,绑定style

<div class="item" :style="{ color: activeIndex == index?'red':'blue' }" v-for="(item, index) in students" @click="itemClick(index)">
        学生编号:{{ item.id }}
        学生姓名:{{ item.name }}
    </div> 
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

更多:

Vue 表单输入绑定,双向绑定
Vue生命周期_Vue生命周期钩子
Vue 概念、历史、发展和Vue简介
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值