VueJs Class 与 Style 绑定 用在组件上

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

应用介绍

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

这个章节假设你已经对 Vue 组件有一定的了解。当然你也可以先跳过这里,稍后再回过头来看。

当在一个自定义组件上使用 class 属性时,这些 class 将被添加到该组件的根元素上面。这个元素上已经存在的 class 不会被覆盖。

例如,如果你声明了这个组件:

Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})

然后在使用它的时候添加一些 class:

<my-component class="baz boo"></my-component>

HTML 将被渲染为:

<p class="foo bar baz boo">Hi</p>

对于带数据绑定 class 也同样适用:

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

当 isActive 为 truthy[1] 时,HTML 将被渲染成为:

<p class="foo bar active">Hi</p>

演示案例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Class 与 Style 绑定->绑定HTML CLASS 对象语法</title>
        <script src="vue.js"></script>
    </head>
    <body>
        <div id="app">
            <my-component class="baz boo"></my-component>
            <my-component v-bind:class="{ active: isActive }"></my-component>
        </div>
        <script type='text/javascript'>
            Vue.component('my-component', {
              template: '<p class="static foo bar">Hi</p>'
            });
            var app = new Vue({
                el: '#app',
                data: {
                  isActive: true,
                }
            });
        </script>
        <style>
            .static{
                color: #333;
                padding: 0.5rem;
                margin: 0.1rem;

            }
            .text-danger{
                color: #ff3b1d;
            }
            .active{
                background:#f5f5f5;
            }
        </style>
    </body>
</html>
点赞(2) 打赏

立即下载

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部