Vue样式绑定---kalrry
一、简介
vue常用样式绑定有两种方式:
- class样式绑定
- style样式绑定
二、class样式绑定
1、对象绑定方式
格式: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>
2、数据绑定方式
格式: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>
3、对象与数据结合的绑定方式
例子
<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
}
}
})
三、class样式绑定
1、对象绑定
格式: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>
2、数组绑定
数组绑定以对象绑定为基础,数组元素是一个个样式对象
格式: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>