Vue.js 之 Class与Style绑定

Class 与 Style 绑定

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

绑定 HTML Class

#对象语法

我们可以传给v-bind:class 一个对象,以动态地切换class。

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

上面的语法表示class active 的更新将取决于数据属性isActive是否为true。

我们也可以在对象中传入更多属性用来动态切换多个class。此外,v-bind:class 指令可以与普通的class属性共存。例如:

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

如下data:

data:{
   isActive:true,
   hasError:false
}

渲染为:

<div class="static active"></div>

isActive 或者 hasError 变化时,class列表将相应地更新。例如,如果hasError的值为true,class列表将变为“static active text-danger”。

你也可以直接绑定数据里的一个对象:

<div v-bind:class="classObject"></div>
data:{
   classObject:{
     active:true,
     'text-danger':false
}
}

渲染的结果和上面一样。我们也可以在这里绑定返回对象的计算属性,这是一个常用且强大的模式:

<div v-bind:class="classObject"></div>
   data:{
     isActive:true,
     error:null
},
   computed:{
     classObject:function(){
       return{
         active:this.isActive && !this.error;
         'text-danger':this.error && this.error.type === 'fatal';
}
}
}

#用在组件上

当你在一个定制的组件上用到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>

-----------------------------------------------------------------------------------------------------------

绑定内联样式

#对象语法

v-bind:style 的对象语法十分直观——看着非常像css,其实它是一个JavaScript对象。

<div v-bind:style="{ color:activeColor,fontSize:fontSize + 'px' }"></div>
   data:{
     activeColor:'red',
     fontSize:30
}

直接绑定到一个样式对象通常更好,让模板更清晰:

<div v-bind:style="styleObject"></div>
   data:{
     styleObject:{
       color:'red',
       fontSize:'30px'
}
}

同样的,对象语法常常结合返回对象的计算属性使用。

 

#数组语法

v-bind:style 的数组语法可以将多个样式对象应用到一个元素上:

<div v-bind:style="[baseStyles,overridingStyles]"></div>

 

 

猜你喜欢

转载自blog.csdn.net/Singularinty/article/details/80859993