1、绑定内联式
代码:
<div id="app">
<!-- 绑定样式属性 -->
<div v-bind:style="{backgroundColor:pink,width:width,height:height}">
<!-- 绑定样式对象 -->
<div v-bind:style="myDiv"></div>
</div>
</div>
<script>
var vm=new Vue({
el: '#app',
data:{
myDiv:{
backgroundColor: 'red',
width: '100px',
height: ' 100px',
},
pink: 'pink',
width: '100%',
height: '200px'
}
});
</script>
2、绑定样式类名
代码:
<style>
.box{
background-color: pink;
width: 100%;
height: 200px;
}
.inner{
background-color: red;
width: 100px;
height: 50px;
border: 2px solid white;
}
</style>
<div id="app">
<div v-bind:class="{box}">我是box
<div v-bind:class="{inner}">我是inner</div>
<div v-bind:class="{inner}">我是inner</div>
</div>
</div>
<script>
var vm=new Vue({
el: '#app',
data: {
box: 'box',
inner: 'inner'
}
});
</script>
绑定样式类名时,在data中的属性存放样式名时,可以分三种方法,给有千秋。
data里的属性可以
1、直接是字符串box: ‘box’;(应用:点击按钮,直接指定样式)
2、是数组classArr:[‘box’,‘inner’];(应用:点击按钮,随机样式)
3、是对象classObj:{box:true,inner:false}(应用:点击按钮,选择样式是否打开)

本文介绍了在 Vue.js 中如何使用 `v-bind:style` 动态绑定样式属性和对象,以及 `v-bind:class` 绑定样式类名的方法。通过示例代码展示了直接使用字符串、数组和对象来控制元素的样式类名,适用于不同场景的需求,如按钮点击切换样式等。
840

被折叠的 条评论
为什么被折叠?



