vue series (7) the type of binding dynamic CSS

class lists and inline style operating element is a common demand for data binding. Because they are property, so we can deal with them with v-bind: just need to figure out the string can result through expression. However, string concatenation cumbersome and error-prone. Therefore, when the v-bind for class and style, Vue.js do a special enhancements. In addition to the result of the expression of type string, and it may be an object or an array.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue.js</title>
	<script src="https://cdn.jsdelivr.net/npm/vue"></script>
	<link rel="stylesheet" type="text/css" href="style.css">
	
</head>
<body>
	<div id="app">
		<h1>动态CSS Class</h1>
		<h2>示例1</h2>
			<div  v-on:click="changeColor = !changeColor" v-bind:class="{changeColor:changeColor}">
				<span>Herry</span>
			</div>
		<button v-on:click="changeColor= !changeColor">change Color</button>
		<button v-on:click="changeLength = !changeLength">changeLength</button>
		<h2>示例2</h2>
		<div v-bind:class="compClass">
			<span>Herry</span>
		</div>
		
	<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

new Vue({
	el: '#app',
	data: {
		changeColor: false,
		changeLength: false
	},
	methods: {
		
	},
	computed: {
		compClass: function() {
			return {
				changeColor: this.changeColor,
				changeLength: this.changeLength
			}
		}
	}
});

style.css

span {
	background: red;
	display: inline-block;
	padding: 10px;
	color: #fff;
	margin: 10px 0;
}
.changeColor span {
	background-color: green;
}
.changeLength span:after {
	content: "length";
	margin-left: 10px;
}

 

Guess you like

Origin blog.csdn.net/jsqfengbao/article/details/94740295