• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ellaha
博客园    首页    新随笔    联系   管理    订阅  订阅
Vue中通过属性绑定为元素设置class

1,直接传递一个数组

2,在数组中使用三元表达式

3,在数组中使用对象代替三元表达式

4,通过对象绑定

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style>
        .red {
            color: red;
        }
        .thin {
            font-weight: 200;
        }
        .italic {
            font-style: italic;
        }
        .active {
            letter-spacing: 4em;
        }
    </style>
</head>
<body>
<div id="div1">
    <!--<h1 class="red thin">你好明天</h1>-->
    <!--第一种方式,直接传递一个数组,注意:这里的class需要使用v-bind做数据绑定-->
    <!--<h1 :class="['red', 'thin']">你好明天</h1>-->
    <!--在数组中使用三元表达式-->
    <!--<h1 :class="['red', 'thin', flag ? 'active': '']">你好明天</h1>-->
    <!--在数组中使用对象代替三元表达式,提高代码可读性-->
    <!--<h1 :class="['red', 'thin', {'active': flag}]">你好明天</h1>-->
    <!--在为class使用v-bind绑定对象时,对象的属性是类名,由于对象的属性可带引号 也可不带引号
    属性值是一个标识符-->
    <!--<h1 :class="{red: true, thin: true, active: true}">你好明天</h1>-->
    <h1 :class="obj">你好明天</h1>
</div>
<script>
    var vm = new Vue({
        el: "#div1",
        data: {
            flag: true,
            obj: {red: true, thin: true, active: true}
        }
    })
</script>
</body>

 

posted on 2021-03-30 22:40  ellaha  阅读(909)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3