class綁定
1.class對象綁定
先看代碼:
<style type="text/css">
.active{color:red;}
</style>
active 這個(gè) class 存在與否將取決于數(shù)據(jù)屬性 isactive 的 truthiness
<body>
<div id="app">
<div @click="handleClick" :class="{active:isactive}">
hello world
</div>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
isactive:false
},
methods:{
handleClick:function(){
this.isactive = !this.isactive
}
}
})
</script>
</body>
2.class數(shù)組綁定
先看代碼:
<div id="app">
<div :class="[active]" @click="handleDivClick">hello world</div>
</div>
這里綁定的class是以數(shù)組的形式,在data里定義一個(gè)active變量為空衰琐。
<script>
var app = new Vue({
el:'#app',
data:{
active:''
},
methods:{
handleClick:function(){
this.active = "active"
}
}
})
</script>
點(diǎn)擊時(shí)哪亿,把class名為active的值賦值給this.active。
此時(shí)翠肘,效果是點(diǎn)擊之后文字顏色變紅,可是再次點(diǎn)擊就沒反應(yīng),只需要改下代碼
methods:{
handleClick:function(){
this.active = this.active == "active" ? "" :"active"
}
}
style綁定
1.style對象綁定
先看代碼:
<body>
<div id="app">
<div @click="handleClick" :style="styleObj">
hello world
</div>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
styleObj:{
color:"#333"
}
},
methods:{
handleClick:function(){
this.styleObj.color = this.styleObj.color==="red"?"#333":"red"
}
}
})
</script>
</body>
這里給div綁定一個(gè)style嚎花,值為styleObj。
先在data里定義styleObj赴邻,里面放著樣式內(nèi)容印衔。然后點(diǎn)擊,切換顏色樣式
2.style數(shù)組綁定
先看代碼:
用數(shù)組的方式綁定style時(shí)姥敛,可以放入多組對象奸焙,如下代碼
<div id="app">
<div @click="handleClick" :style="[styleObj,{background:'#ccc'}]">
hello world
</div>
</div>