Vue学习(八): Vue中的使用样式

使用Class样式

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

  2. 数组里面的三元表达式

<h1 :class="['red','thin',flag?'active':'']">这是H1</h1>
  1. 数组使用对象代替三元表达式,提高代码的可读性
    <h1 :class="['red','thin',{'active':flag} ]">这是H1</h1>

  2. 直接对象
    在为class使用v-bind绑定对象的时候,对象的属性是类名,对象的属性可以不需要引号;属性的值是一个标识符

<h1 :class="{red:false, thin: true, italic:true, active:false}">这是H1</h1>

代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>
<body>
    <style>
    .red{
        color:red;
    }
    .thin{
        font-weight: 100;
    }
    .italic{
        font-style: italic
    }
    .active{
        letter-spacing: 0.5em;
    }
    </style>
</body>
<div id="app">
     <!--数组-->
    <h1 :class="['red','thin']">这是H1</h1>
    <!--三元表达式-->
    <h1 :class="['red','thin',flag?'active':'']">这是H1</h1>
    <!--数组使用对象代替三元表达式,提高代码的可读性-->
    <h1 :class="['red','thin',{'active':flag} ]">这是H1</h1>
    <!--对象-->
    <h1 :class="{red:false, thin: true, italic:true, active:false}">这是H1</h1>
     <!--直接指向-->
     <h1 :class="classobj">这是H1</h1>
</div>
<script>
var vm = new Vue({
    el: '#app',
    data:{
        flag : true,
        classobj: {red:false, thin: true, italic:true, active:false}
    },
    methods:{

    }
})
</script>
</html>

使用内联样式

  1. 直接在元素上通过:style 的形式,书写样式对象
    <h1 :style="{ color:'red', 'font-weight':100 }">这是H1</h1>
  2. 将样式对象,定义到data中,并直接引用到:style
<div id="app">
        <!--对象就是无序键值对的集合-->
        <h1 :style="styleobj">这是H1</h1>
    </div>
    <script>
    var vm = new Vue({
        el: '#app',
        data:{
            styleobj : { color:'red', 'font-weight':100 }
        },
        methods:{

        }
    })
    </script>
  1. :style 中通过数组引用多个 data 上的样式对象
<div id="app">
        <!--对象就是无序键值对的集合-->
        <h1 :style="[styleobj,styleobj2]">这是H1</h1>
    </div>
    <script>
    var vm = new Vue({
        el: '#app',
        data:{
            styleobj : { color:'red', 'font-weight':100 },
            styleobj2 : { 'font-style': 'italic' }
        },
        methods:{

        }
    })
    </script>