vue

Vue学习笔记(六)之Vue中的样式绑定

Posted by weite122 on 2018-08-24

Vue中的样式绑定

对象语法

  • 效果
  • 代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Vue中的样式绑定</title>
    <script src="http://vuejs.org/js/vue.js"></script>
    <style>
    .activated {
    color: red;
    }
    </style>
    </head>
    <body>
    <div id="app">
    <div @click="handleDivClick"
    :class="{activated: isActivated}">
    Hello World
    </div>
    </div>
    <script>
    var vm = new Vue({
    el: "#app",
    data: {
    isActivated: false
    },
    methods: {
    handleDivClick: function () {
    this.isActivated = !this.isActivated
    }
    }
    })
    </script>
    </body>
    </html>

数组语法

  • 效果
  • 代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Vue中的样式绑定</title>
    <script src="http://vuejs.org/js/vue.js"></script>
    <style>
    .activated {
    color: red;
    }
    </style>
    </head>
    <body>
    <div id="app">
    <div @click="handleDivClick"
    :class="[activated]">
    Hello World
    </div>
    </div>
    <script>
    var vm = new Vue({
    el: "#app",
    data: {
    activated: ""
    },
    methods: {
    handleDivClick: function () {
    // if (this.activated === "activated") {
    // this.activated = ""
    // }else {
    // this.activated = "activated"
    // }

    this.activated = this.activated === "activated" ? " " : "activated" //三元表达式
    }
    }
    })
    </script>
    </body>
    </html>

绑定内联样式

  • 效果

  • 代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Vue中的样式绑定</title>
    <script src="http://vuejs.org/js/vue.js"></script>
    </head>
    <body>
    <div id="app">
    <div @click="handleDivClick"
    :style="[styleObj, {fontSize: '30px'}]">
    Hello World
    <!-- js引用css时必须使用驼峰命名 -->
    </div>
    </div>
    <script>
    var vm = new Vue({
    el: "#app",
    data: {
    styleObj: {
    color: "black",
    }
    },
    methods: {
    handleDivClick: function () {
    this.styleObj.color = this.styleObj.color === "red" ? "black" : "red"
    }
    }
    })
    </script>
    </body>
    </html>
  • style内联绑定既可以使用数组,也可以使用对象绑定。