vue动态绑定属性--动态绑定style
动态绑定style
使用v-bind:style绑定css内联样式,写属性名时,使用驼峰式或短横分隔(单引号括起来),如属性font-size,驼峰式写法fontSize,短横写法:'font-size'
1.对象语法
语法格式::style="{属性名:属性值,属性名:属性值}"
<body>
<!-- v-bind绑定style--对象语法 (多)-->
<h2 :style="{fontSize:'50px'}">v-bind绑定style</h2>
<h2 :style="{fontSize: finalSize + 'px', backgroundColor: finalColor}">v-bind绑定style</h2>
</div>
<script src="../js/vue.js"></script>
<script>
setTimeout(function() {
const vm = new Vue({
el: '#app',
data: {
msg: 'hello',
finalSize: 20,
finalColor: 'pink',
}
});
},2000);
</script>
</body>
2.数组语法
<body>
<!-- v-bind绑定style--数组语法 -->
<h3 :style="[baseStyle]">v-bind绑定style--数组语法 </h3>
</div>
<script src="../js/vue.js"></script>
<script>
setTimeout(function() {
const vm = new Vue({
el: '#app',
data: {
baseStyle: {
backgroundColor: 'red'
}
},
});
},2000);
</script>
</body>
当绑定的对象或数组太长时,可以使用计算属性或方法将其返回,以对象语法为例
<body>
<!-- v-bind绑定style--对象语法 (多)-->
<h2 :style="getStyleObj()">v-bind绑定style--对象语法 (多)-</h2>
<script src="../js/vue.js"></script>
<script>
setTimeout(function() {
const vm = new Vue({
el: '#app',
data: {
msg: 'hello',
finalSize: 20,
finalColor: 'pink',
},
methods: {
getStyleObj(){
return {fontSize: this.finalSize + 'px', backgroundColor: this.finalColor}
}
},
});
},2000);
</script>
</body>
本文来自博客园,作者:jxweber,转载请注明原文链接:https://www.cnblogs.com/jxweber/p/16139495.html
浙公网安备 33010602011771号