绑定方式一:对象语法
:style="{key(属性名),value(属性值)}"
style后面跟的是一个对象名称
- 对象的key是CSS属性名称;
- 对象的value是具体赋值,可以来自于data中的属性
例 :style="{color:currentColor,fontSize:fontSize + 'px'}"
效果展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>05-vBind动态绑定style(对象语法)</title>
<link rel="shortcut icon" type="image/x-icon" href="../img/Vue.png"/>
</head>
<body>
<div id="dynamic">
<!--<h2 :style="{key(属性名),value(属性值)}">{{messgae}}</h2>-->
<!--'50px'必须加上单引号,否则会当做一个变量去解析-->
<!--<h2 :style="{fontSize:'50px'}">{{messgae}}</h2>-->
<!--finalSize变量只跟单一的数字,也会被当一个变量去解析-->
<!-- <h2 :style="{fontSize:finalSize}"> {{messgae}} </h2> -->
<h2 :style="{fontSize:finalSize +'px',backgroundColor:finalColor}"> {{messgae}} </h2>
<!--简写-->
<h2 :style="getStyle()">{{messgae}}</h2>
</div>
<script src="../文件/vue.js"></script>
<script>
const dynamic = new Vue({
el:'#dynamic',
data:{
messgae:'你好啊',
finalSize:100,
finalColor:'yellow',
},
methods:{
getStyle:function(){
return{fontSize:this. finalSize +'px',backgroundColor:this. finalColor}
}
}
})
</script>
</body>
</html>
绑定方式二:数组语法
style后面跟的是一个数组类型
- 多个值,分割即可
例 :style="[baseStyles,overridingStyles]"
效果展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>05-vBind动态绑定style(对象语法)</title>
<link rel="shortcut icon" type="image/x-icon" href="../img/Vue.png"/>
</head>
<body>
<div id="dynamic">
<!--对象数组-->
<h2 :style="[baseStyles,overridingStyles]">{{messgae}}</h2>
</div>
<script src="../文件/vue.js"></script>
<script>
const dynamic = new Vue({
el:'#dynamic',
data:{
messgae:'你好啊',
baseStyles:{fontSize:'100px'},
overridingStyles:{backgroundColor:'#6495ED'}
}
})
</script>
</body>
</html>