5 style和class
数据的绑定
语法
:属性名=js变量/js语法
- :class=’js变量、字符串、js数组’
class:三目运算符、数组、对象{red: true}
- :style=’js变量、字符串、js数组’
style:三目运算符、数组[{backgreound: ‘red’},]、对象{background: ‘red’}
style和class都能绑定字符串,数组,对象
class绑定字符串,数组,对象(推荐使用数组)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <style> .red{ background-color: red; } .green{ background-color: green; } .size{ font-size: 60px; } </style> </head> <body> <div class="app"> <!-- <button @click="handleClick">点我变色</button>--> <!-- <button @click="handleClick2">点我字体变大</button>--> <button @click="handleClick3">点我字体变大2</button> <div :class="divClass"> <p>我是div</p> </div> </div> </body> <script> var vm = new Vue({ el: '.app', data: { // class 属性,绑定字符串 // divClass:'red' //class 属性,绑定数组----这个用的多 // divClass:['red',] // class属性,绑定对象 divClass:{'red':true,'size':false} }, methods: { // handleClick() { // this.divClass='green' //点击,背景变为蓝色 // }, // handleClick2(){ // this.divClass.push('size') //点击,改变字体 // } handleClick3(){ this.divClass['size']=true //点击,改变字体 } } }) </script> </html>
style绑定字符串,数组,对象(推荐使用对象)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> </head> <body> <div class="app"> <div :style="styleStr"> <p>我是div</p> </div> </div> </body> <script> var vm = new Vue({ el: '.app', data: { //style绑定字符串 // styleStr:'background-color: red;font-size: 40px' // style绑定数组 // styleStr:[{'background-color':'green'},{'font-size': '40px'}] // style绑定对象 // styleStr:{'background-color':'yellow','font-size': '80px'} styleStr:{backgroundColor:'yellow',fontSize: '80px'} // 驼峰会自动转换 }, methods: {} }) </script> </html>