前端vue学习曲线(8)class与style绑定

本文详细探讨了Vue.js中class和style的三种绑定语法:内联语法、对象语法和数组语法,通过实例解析帮助读者更好地理解和掌握这些绑定机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.内联语法

<div id="app1" class="static"  v-bind:class="{active:isActive,'text-danger':hasError}"></div>
var app1 = new Vue({
		el: "#app1",
		data: {
			isActive: true,
			hasError: false
		}
    })

<div id="app4" :style="{color:activeColor,fontSize:fontSize+'px'}"></div>
var app4 = new Vue({
		el: "#app4",
		data: {
			activeColor: 'red',
			fontSize: 30
		}
	})

2.对象语法

<div v-bind:class="classObject">传对象</div>
var app1 = new Vue({
		el: "#app1",
		data: {
			classObject: {
				active: true,
				'text-danger': true
			}
		}
	})


<div id="app5" :style="styleObject">#样式对象</div>
var app5 = new Vue({
		el: "#app5",
		data: {
			styleObject: {
				color: '#4848',
				fontSize: '13px'
			}
		}
	})

3.数组语法

<div id="app3" v-bind:class="[activeClass,errorClass]">数组</div>
var app3 = new Vue({
		el: "#app3",
		data: {
			activeClass: 'active',
			errorClass: 'text-danger'
		}
})

例子:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	</head>

	<body>
		<h3>class</h3>
		<h4>#对象语法</h4>
		<div id="app1" class="static" v-bind:class="{active:isActive,'text-danger':hasError}">
			<div v-bind:class="classObject">传对象</div>
		</div>
		<div id="app2" v-bind:class="classObject1">计算属性</div>
		</div>
		<h4>#数组语法</h4>
		<div id="app3" v-bind:class="[activeClass,errorClass]">数组</div>
		<a href="https://cn.vuejs.org/v2/guide/class-and-style.html#用在组件上">用在组件上</a>
		<h3>style</h3>
		<div id="app4" :style="{color:activeColor,fontSize:fontSize+'px'}">
			#对象语法
		</div>
		<div id="app5" :style="styleObject">#样式对象</div>
	</body>

</html>
<script>
	var app1 = new Vue({
		el: "#app1",
		data: {
			isActive: true,
			hasError: false,
			classObject: {
				active: true,
				'text-danger': true
			}
		}
	})
	var app2 = new Vue({
		el: "#app2",
		data: {
			isActive: true,
			error: null
		},
		computed: {
			classObject1: function() {
				return {
					active: this.isActive && !this.error,
					'text-danger': this.error && this.error.type === 'fatal'
				}
			}
		}
	})
	var app3 = new Vue({
		el: "#app3",
		data: {
			activeClass: 'active',
			errorClass: 'text-danger'
		}
	})
	var app4 = new Vue({
		el: "#app4",
		data: {
			activeColor: 'red',
			fontSize: 30
		}
	})
	var app5 = new Vue({
		el: "#app5",
		data: {
			styleObject: {
				color: '#4848',
				fontSize: '13px'
			}
		}
	})
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值