今天复习vue,突然发现关于样式绑定这部分忘记写了,在这里补充一下
vue绑定样式分为两种:class样式和style样式
class样式
对象绑定
格式:v-bind:class="{styleClass:flog}"
styleClass:定义好的样式类
flog:布尔值,表示样式是否显示
实例
<style type="text/css">
.style1 {
width: 100px;
height: 100px;
border: 1px solid red;
}
.style2 {
background-color: orange;
}
</style>
<body>
<div id="app">
<div :class="{style1:isS1,style2:isS2,....}">vue样式绑定</div>
<button @click="change">切换样式</button>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
isS1: true,
isS2: true
},
methods: {
change() {
this.isS1 = !this.isS1;
this.isS2 = !this.isS2;
}
}
})
</script>
</body>
数组绑定
格式:v-bind:class="[样式变量1,样式变量2,.....]"
实例
<style type="text/css">
.style1 {
width: 100px;
height: 100px;
border: 1px solid red;
}
.style2 {
background-color: orange;
}
</style>
<body>
<div id="app">
<div :class="[hasBgColor,hasBorder]">vue样式绑定</div>
<button @click="change">切换样式</button>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
hasBorder: 'style1',
hasBgColor: 'style2'
},
methods: {
change() {
this.hasBgColor = ''
}
}
})
</script>
</body>
结合使用
<style type="text/css">
.style1 {
width: 100px;
height: 100px;
border: 1px solid red;
}
.style2 {
background-color: orange;
}
</style>
<div :class="[hasBgColor,{style2:flog}]">vue样式绑定</div>
new Vue({
el: '#app',
data: {
hasBorder: 'style1',
flog: true
},
methods: {
change() {
this.flog = !this.flog
}
}
})
style样式
对象绑定
格式:v-bind:style="{样式:值,.......}"
<body>
<div id="app">
<div v-bind:style="{border:borderStyle,width:widthStyle,height:heightStyle}">vue样式绑定</div>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
borderStyle:'1px solid red',
widthStyle: '100px',
heightStyle:'100px'
}
})
</script>
</body>
数组绑定
数组绑定以对象绑定为基础,数组元素是一个个样式对象
格式:v-bind:style="[样式1,样式2,...]"
<body>
<div id="app">
<div v-bind:style="[baseStyle,fontStyle]">vue样式绑定</div>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
baseStyle: {
border: '1px solid red',
width: '100px',
height: '100px'
},
fontStyle: {
fontFamily: '宋体',
fontSize: '20px',
color:'blue'
}
}
})
</script>
</body>