一、class样式
写法::class="xxx" xxx可以是字符串、对象、数组。
1.字符串写法适用于:类名不确定,要动态获取。
HTML代码:
<div class="basic" :class='mood' @click='changeMood'>{{name}}</div><br><br>
JavaScript代码:
<script>
Vue.config.productionTip = false
const vm=new Vue({
el:'#root',
data:{
name:'尚硅谷',
mood:'normal',//normal为样式名
},
methods: {
changeMood(){
const arr=['normal','happy','sad']
const index=Math.floor(Math.random()*3)
this.mood=arr[index]
}
},
})
</script>
2.。数组写法,适用于:要绑定的样式个数确定,名字也确定,但要动态决定用不用
HTML代码:
<div class="basic" :class='classArr'>{{name}}</div><br><br>
JavaScript代码:
<script>
Vue.config.productionTip = false
const vm=new Vue({
el:'#root',
data:{
name:'尚硅谷',
classArr:['atguigu1','atguigu2','atguigu3']
//atguigu1、2、3、为样式名
},
})
</script>
3.对象写法适用于:要绑定的样式个数不确定,名字也不确定
HTML代码:
<div class="basic" :class='classObj'>{{name}}</div><br><br>
JavaScript代码:
<script>
Vue.config.productionTip = false
const vm=new Vue({
el:'#root',
data:{
name:'尚硅谷',
classObj:{
atguigu1:false,
atguigu2:false
}
}
})
</script>
二、绑定style样式
写法:
:style="{fontSize:xxx}",其中xxx是动态值。
:style="[a,b]"其中a、b是样式对象
1.对象写法:
HTML代码:
<div class="basic" :style="styleObj1">{{name}}</div><br><br>
JavaScript代码:
<script>
Vue.config.productionTip = false
const vm=new Vue({
el:'#root',
data:{
name:'尚硅谷',
styleObj1:{
fontSize:'40px'
}
}
})
</script>
2.数组写法:
HTML代码:
<div class="basic" :style="[styleObj1,styleObj2]">{{name}}</div>
JavaScript代码:
<script>
Vue.config.productionTip = false
const vm=new Vue({
el:'#root',
data:{
name:'尚硅谷',
styleObj1:{
fontSize:'40px'
},
styleObj2:{
backgroundColor:'blue'
}
}
})
</script>