在vue中使用样式的方法

一、vue属性绑定

在vue中,是通过v-bind 属性绑定来实现给元素绑定style样式。

其中有两种方式,一种是通过绑定class类绑定样式,另一种是通过内联样式来实现样式的绑定。

二、绑定class样式

1. 数组
<h1 :class="['red', 'thin']">这是一个邪恶的H1</h1>

2. 数组中使用三元表达式
<h1 :class="['red', 'thin', isactive?'active':'']">这是一个邪恶的H1</h1>

3. 数组中嵌套对象
<h1 :class="['red', 'thin', {'active': isactive}]">这是一个邪恶的H1</h1> 4. 直接使用对象 <h1 :class="{red:true, italic:true, active:true, thin:true}">这是一个邪恶的H1</h1>
<style>
     .red {
      color: red;
    }

    .thin {
      font-weight: 200;
    }

    .italic {   /*字体倾斜*/
      font-style: italic;
    }

    .active {       /*字符间距*/
      letter-spacing: 0.5em;
    }
</style>
<body>
    <div id='app'>
        <!-- v-bind:等同于: -->
        <!-- 第一种使用方式,直接传递一个数组,注意: 这里的 class 需要使用  v-bind 做数据绑定 --> 
        <h3 v-bind:class=['red','thin']>今天永远比昨天更好</h3>
        <!-- 在数组中使用三元表达式 -->
        <h3 v-bind:class=['red','thin',flag?'active':'']>今天永远比昨天更好</h3>
        <!-- 在数组中使用 对象(即键值对的方式)来代替三元表达式,提高代码的可读性 -->
        <h3 v-bind:class=['red','thin',{'active':flag}]>今天永远比昨天更好</h3>
        <!-- 在为 class 使用 v-bind 绑定 对象的时候,对象的属性是类名,由于 对象的属性可带引号,也可不带引号,所以 这里我没写引号;  属性的值 是一个标识符 -->
        <h3 :class="classObj">今天永远比昨天更好</h1>
    </div>
    
</body>
<script src="vue-2.4.0.js"></script>
<script>
    var vm = new Vue({
        el:'#app',
        data:{
            flag:true,
            classObj:{
                red: true, thin: true, italic: false, active: false 
            }
        }
    })
</script>
</html>

三、绑定内联样式

1. 直接在元素上通过 `:style` 的形式,书写样式对象
<h1 :style="{color: 'red', 'font-size': '40px'}">这是一个善良的H1</h1>

2. 将样式对象,定义到 `data` 中,并直接引用到 `:style` 中
 + 在data上定义样式:
data: {
        h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }
}
 + 在元素中,通过属性绑定的形式,将样式对象应用到元素中:

<h1 :style="h1StyleObj">这是一个善良的H1</h1>

3. 在 `:style` 中通过数组,引用多个 `data` 上的样式对象
 + 在data上定义样式:
data: {
        h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' },
        h1StyleObj2: { fontStyle: 'italic' }
}
 + 在元素中,通过属性绑定的形式,将样式对象应用到元素中:
```
<h1 :style="[h1StyleObj, h1StyleObj2]">这是一个善良的H1</h1>
原文地址:https://www.cnblogs.com/starwei/p/12487892.html