<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.bgBlue{
background: skyblue;
}
.bgPink{
background: pink;
}
.div1{
width: 300px;
height: 300px;
margin: 0 auto;
}
#div1{
width: 300px;
height: 300px;
margin: 0 auto;
}
</style>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<div :class="color">
</div>
<button @click='changeColor'>更改颜色</button>
<hr />
<div :class="color2">
</div>
<button @click='changeColor2'>更改颜色</button>
<hr />
<div :class="color3">
</div>
<button @click='changeColor3'>更改颜色</button>
<hr />
<div :class="['div1',divBG]">
</div>
<button @click='changeColor4'>更改颜色</button>
<hr />
<!--
vue给class属性专门定制了绑定的方式,那么不会删除默认class里面的值,而是进行添加的方式,将绑定变量里面的值放入class
-->
<div data-key='123' :data-key='msg' class="123" :class="['div1',{bgPink:!isBlue},{bgBlue:isBlue}]">
</div>
<button @click='changeColor5'>更改颜色</button>
</div>
<script type="text/javascript">
var app = new Vue({
el:'#app',
data:{
color:'div1 bgBlue',
color2:{
div1:true,
bgBlue:true,
bgPink:false
},
color3:[ 'div1','bgBlue' ],
divBG:'bgBlue',
isBlue:true,
msg:'hello'
},
methods:{
changeColor:function(){
this.color = 'div1 bgPink'
},
changeColor2:function(){
this.color2 = {
div1:true,
bgBlue:false,
bgPink:true
}
},
changeColor3:function(){
this.color3 = ['div1','bgPink']
//新建了1个数组,将老的内存地址覆盖掉
//this.color3[1] = 'bgPink',因为这样并没有更改掉color3内存地址没有更改掉,所以不会触发视图的更新
//this.$set(this.color3,1,'bgPink')
},
changeColor4:function(){
this.divBG = 'bgPink'
},
changeColor5:function(){
this.isBlue = false
}
}
})
</script>
<!--
1、class属性绑定变量,变量是相对应的classname的字符串
2、使用对象的方式来绑定class,根据对象里的属性值是否是true,来决定这个属性是否添加进class
3、数组的形式
-->
</body>
</html>