vue框架绑定class属性的几种方式

操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是 attribute,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。

v-bind:class 一个对象,以动态地切换 class:

<div v-bind:class="{ active: isActive }"></div>

你可以在对象中传入更多字段来动态切换多个 class

<div
  class="static"
  v-bind:class="{ active: isActive, 'text-danger': hasError }"

></div>

给大家看一下我做的示例吧

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="vue.js"></script>
    <style>
        .hide{
            display: none;
        }
    </style>
</head>
<body>
    <!-- v-bind:class 绑定class属性 -->
   <div id="vuediv">
    <div class="defaultClass" v-bind:class="classObj">洛洛大芳</div>
   </div>
</body>
<script>
    var vm=new Vue({
        el:"#vuediv",
        data() {
            return {
                // isHide:false,
                // haserror:false
                classObj:{
                    isHide:false,
                    haserror:false
                }
            }
        },
        })
</script>
</html>

接下来看绑定内联样式数组形式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="vue.js"></script>
</head>
<body>
    <div id="vuediv">
        <div v-bind:style="[ArrayA,ArrayB]">洛洛大芳</div>
    </div>
</body>
<script>
    var vm=new Vue({
        el:"#vuediv",
        data() {
            return {
           ArrayA:{
               width:'100px',
               height:'40px'
           },
           ArrayB:{
               "background-color":'red',
           },
            }
        }
    })
</script>
</html>

除了以上两种方式还有对象的形式绑定class属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="vue.js"></script>
</head>
<body>
    <div id="vuediv">
        <div v-bind:style="styleObj">洛洛大芳</div>
    </div>
</body>
<script>
    var vm=new Vue({
        el:"#vuediv",
        data() {
            return {
            styleObj:{
                width:'100px',
                height:'40px',
                'background-color':"red"
            }
            }
        },
    })
</script>
</html>

差不多就这些了吧,好好学习天天向上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值