通过class列表和style指定样式是数据绑定的一个常见需求。它们都是元素的属性,都用v-bind处理,其中表达式结果的类型可以是:
- 字符串、对象或数组。
-
语法格式
v-bind:class=‘表达式’
或
:class=‘表达式’
class 的表达式可以为:
字符串: class=“activeClass”
对象: class="{active: isActive, error: hasError}"
数组: class="[‘active’, ‘error’]"注意要加上单引号,不然是获取data中的值
v-bind:style='表达式’或:style=‘表达式’
style 的表达式一般为对象:style="{color: activeColor, fontSize: fontSize + ‘px’}"
注意:对象中的value值 activeColor 和 fontSize 是data中的属性
绑定对象类型:
代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <style>
- .active {
- color: red;
- }
- .size {
- font-size: 30px;
- }
- </style>
- <body>
- <div id="app">
- <!--当isActive为true 渲染active样式 当isSize为true 渲染size样式-->
- <h2 v-bind:class="{active: isActive,size: isSize}">{{msg}}</h2>
- <button v-on:click="change">按钮</button>
- </div>
- <script src="../js/vue.js"></script>
- <script type="text/javascript">
- const vm = new Vue({
- el: "#app",
- data: {
- msg: "你好啊",
- isActive: true,
- isSize: false
- },
- methods: {
- change: function () {
- this.isActive = !this.isActive
- this.isSize = !this.isSize
- }
- }
- })
- </script>
- </body>
- </html>
-
效果: