Vue.js 样式绑定

1.对象语法

(1)使用v-bind为class绑定一个对象,对象的key为样式名,key的值为布尔值。若是为true则添加这个类名,为false则移除这个类名。
这个方法适用class类名肯定,但可能添加,也可能不添加的情形css

.active{
    color:red;
}

<div id="app">
    <p :class="{active:isActive}">今天礼拜四</p>
</div>
var vm = new Vue({
    el:'#app',
    data:{
        isActive:true
    }
})

(2)添加多个类名:添加多个键值对便可
注意:添加多个类名时,key最好加上 引号 否则会报错html

<p :class="{active:isActive,'text-center':isCenter}">今天礼拜四</p>

(3)v-bind:class接收一个对象,能够传递一个对象值给他,也能够用方法或者 计算属性返回一个对象给他均可以vue

computed:{
  classObject:function(){
       return {active:this.isActive,'text-center':this.isCenter}
  }
}
<p :class="classObject">今天礼拜四</p>

2.数组语法

能够把一个数组传给 v-bind:class,以应用一个 class 列表
语法:v-bind:class="[]"
数组元素能够是class类名,也能够是vue定义的变量数组

//直接使用类名
<p :class="['active','text-center']">今天礼拜四</p>
//使用vue定义的变量
<p :class="[activeClass,centerClass]">今天礼拜四</p>
data:{
    activeClass:'active',
    centerClass:'text-center'
}

渲染结果:app

<p class="active text-center">今天礼拜四</p>

3.绑定内联样式

其实就是使用v-bind给style属性绑定值.
(1)对象语法:适合给单个css属性赋值。
语法:v-bind:style="{css属性,属性值}"
(2)数组语法:适合给2个或2个以上的css属性赋值
语法:v-bind:style="[{css属性,属性值},{css属性,属性值}]"
注意:对象中的key不能有 - 这样的字符,text-align要写成textAlignthis

<!-- html语法 -->
<h1 style="color:red">html语法</h1>
<!-- 对象语法 css属性值为字符串-->
<h1 :style="{color:'green'}">对象语法</h1>
<!-- 对象语法 css属性值为vue定义的变量-->
<h1 :style="{color:myColor}">对象语法</h1>
<!-- 数组语法 -->
<h1 :style="[{color:'green'},{textAlign:'center'}]">数组语法</h1>

渲染结果:code

<h1 style="color: red;">html语法</h1>
<h1 style="color: green;">对象语法</h1>
<h1 style="color: blue;">对象语法</h1>
<h1 style="color: green; text-align: center;">数组语法</h1>

4.子组件标签上的class类

若是组件自己已经有class类,而调用组件的时候又给他绑定了新的class类,那么他们不会覆盖,而是会叠加在一块儿htm

//父组件
<child :class="{box:flag}"></Child>
//子组件
<div :class="{child:flag}">
    <p>我是子组件</p>
</div>

渲染结果:对象

<div class="child box"><p>我是子组件1</p></div>
相关文章
相关标签/搜索