Vue style binding---kalrry
1. Introduction
There are two ways to bind common styles in vue:
- class style binding
- style style binding
Second, class style binding
1. Object binding method
Format: v-bind:class="{styleClass:flog}"
styleClass: The defined style class flog
: Boolean value, indicating whether the style is displayed or not
<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. Data binding method
Format: v-bind:class="[style variable 1, style variable 2,...]"
Example
<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. Binding method of object and data combination
example
<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
}
}
})
Three, class style binding
1. Object binding
Format: v-bind:style="{style:value,...}"
Example
<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. Array binding
Array binding is based on object binding, and array elements are style objects
. Format: v-bind:style="[style1,style2,…]"
Example
<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>