Vue样式绑定
(1) 对class 属性进行绑定
1、将类名写在{ }内作为属性名,属性值为true(显示)和false(隐藏)。
利用开关思想就可以写出一个简单的按钮换色效果
<style> .bgc2{ width: 100px; height: 100px; background-color: rgb(0, 0, 0) !important; } .bgc1 { width: 100px; height: 100px; background-color: rgb(247, 20, 20) !important; } </style> <div class="app"> <button @click="fn1">{{aa}}</button> <div :class="{bgc2:true,bgc1:flag}"></div> </div>
new Vue({ el: ".app", data: { aa: "变红", flag: false, }, methods: { fn1() { this.flag = !this.flag if (this.flag) { this.aa = "变黑" } else { this.aa = "变红" } } } } )
界面图
点击按钮之后就会显示
2、直接写变量(如果写了多个变量,那也只会生效第一个)
如将以上代码 添加html代码<div :class="classname"></div>
添加Vue中的data对象的属性 classname:"bgc1"
界面就会多出一个
3、将类名写在[ ]里,和第二种类似,但都会生效
注意 :
- [ ]里边的类名可以是data数据容器里的变量,也可以不是变量(字符串),
用 ' 字符串类名 ' 来表示。 :class="[ 'content' ,classname]"
- [ ] 里边也可以放第一种 { }的类名进去,如:class="[content,{active:true}]"
(2)对style 进行绑定
1、直接写在行内,里边的属性的名称要用驼峰命名方式,如果没用驼峰要加引号
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
2、写成一个对象,再用data传进去
<div v-bind:style="styleObject"></div>
data: { activeColor: 'red', fontSize: 30, red1:"red", styleObject: { color: 'red', fontSize: '13px' } }
3、数组形式
版权声明:本文为m0_63470734原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。