vue学习 10vue-动态绑定CSS样式

本文介绍了Vue中如何使用v-bind:class指令动态绑定CSS样式,通过对象形式实现条件切换class,例如`{changeColor: true}`。详细讲解了在HTML、CSS和JavaScript(app.js)中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标签绑定class属性:v-bind:class="{changeColor: true}"  

注意里面的写法是对象的形式

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Vue.js</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    <!-- vue-app是根容器 -->
    <div id="vue-app">
        <h1> 动态 CSS Class</h1>
        <h2>实例 1</h2>
        <div v-on:click="changeColor=!changeColor"  v-bind:class="{changeColor: changeColor}">
            <span> changeColor </span>
        </div>
        <h2>实例 2</h2>
        <button v-on:click="changeColor=!changeColor"> change color </button>
        <button v-on:click="changeLength=!changeLength"> change length </button>
        <div v-bind:class="compClasses">
            <span>Henry</span>
        </div>
    </div>
    <script src="app.js" type="text/javascript"></script>
</body>
</html>

css

span {
    background: red;
    display: inline-block;
    padding: 10px;
    color: #fff;
    margin: 10px 0;
}

.changeColor span {
    background : blue;
}
.changeLength span:after {
    content: "length";
    margin-left: 20px;
}

app.js

'use strict';
// 实例化vue对象
new Vue({
    el: "#vue-app",
    data: {
        changeColor: false,
        changeLength: false
    },
    methods: {

    },
    computed: {
        compClasses: function(){
            // 返回的是一个对象
            return {
                changeColor: this.changeColor,
                changeLength: this.changeLength
            }
        }
    }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值