Vue绑定style和class 对象写法

适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用。

 绑定 class 样式【对象写法】:

.box{
	width: 100px;
	height: 100px;
}
.aqua{
	background-color: aqua;
}
.border{
	border: 20px solid red;
}
.radius{
	border-radius: 25px;
}
<div id="APP">
	<div class="box" :class="classObj">多个class样式</div>
</div>

const vm = new Vue({
	el: "#APP",
	data(){
		return {
			classObj:{
				aqua: true,
				border: false,
				radius:false
			}
		}
	}
});

:对象写法中的键名必须是 class 类名,值如果为 true 表示使用,如果为 false 表示不使用。当然我们也可以动态修改它的值,选择是否使用。

对象写法也可以直接写在标签中,例:

.box{
	width: 100px;
	height: 100px;
}
.aqua{
	background-color: aqua;
}
.border{
	border: 20px solid red;
}
.radius{
	border-radius: 25px;
}

<div id="APP">
	<div class="box" :class="{aqua:a, border:b, radius:c}">多个class样式</div>
</div>


:效果与上边的示例相同,a、b、c 都是变量,控制是否使用某个 class 样式。

 绑定 style 样式【对象写法】 :

<div id="APP">
	<div :style="styleObj">绑定style样式</div>
</div>

const vm = new Vue({
	el: "#APP",
	data(){
		return {
			styleObj:{
				width: '100px',
				height: '100px',
				backgroundColor: "aqua"
			}
		}
	}
});

:动态绑定 style 样式时,属性必须使用小驼峰命名法,例如:backgroundColor 。 

绑定 style 样式【数组写法】:

<div id="APP">
	<div :style="styleArr">绑定style样式</div>
</div>

const vm = new Vue({
	el: "#APP",
	data(){
		return {
			styleArr:[
				{
					width: "100px",
					height: "100px"
				},
				{
					backgroundColor: "aqua",
					border:"20px solid red"
				}
			]
		}
	}
});

:使用数组写法绑定 style 样式时,数组其实是由多个 样式对象 组成的。

数组写法也可以直接写在标签中,与上面示例的效果相同。

<div id="APP">
	<div :style="[styleObj1,styleObj2]">绑定style样式</div>
</div>

const vm = new Vue({
	el: "#APP",
	data(){
		return {
			styleObj1:{
				width: "100px",
				height: "100px"
			},
			styleObj2:{
				backgroundColor: "aqua",
				border:"20px solid red"
			}
		}
	}
});

原创作者:吴小糖

创作时间:2023.10.13 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小吴吴吴呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值