Vue动态的改变class与style属性值
1.理解
一般在应用界面中, 某个(些)元素的样式是变化的, class/style绑定就是专门用来实现动态样式效果的技术
2.class绑定
html用法 :class=“variable”
其中variable是data中的变量, variable有三种类型: 字符串、对象、数组.
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 41 42 43 44
| <head> <meta charset="UTF-8"> <title>Test</title> <style> .classA { color: red; } .classB { color: blue; } .classC { font-size: 20px; } </style> </head> <body> <div id="demo"> <h2>1. class绑定: :class='xxx'</h2> <p class="classC" :class="myClass">xxx是字符串</p> <p class="classC" :class="{classA:hasClassA,classB:hasClassB}">xxx是对象</p> <p :class="['classA','classC']">xxx是对象</p> <button @click="update">更新</button> </div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { myClass:"classA", hasClassA:false, hasClassB:true, }, methods: { update(){ this.myClass = "classB"; this.hasClassA = !this.hasClassA; this.hasClassB = !this.hasClassB;
} } }) </script> </body>
|
3.style绑定
html用法 :style="{ color: activeColor, fontSize: fontSize + ‘px’ }"
其中activeColor/fontSize是data中的变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <body> <div id="demo"> <h2>2. style绑定</h2> <p :style="{color:activeColor, fontSize: fontSize + 'px'}">:style="{ color: activeColor, fontSize: fontSize + 'px' }"</p> <button @click="update">更新</button> </div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { activeColor:"red", fontSize:20, }, methods: { update(){ this.activeColor = "yellowGreen"; this.fontSize = 50-this.fontSize; } } }); </script> </body>
|