Vue 样式绑定
class对象绑定
通过 :class 和对象,实现样式和数据的绑定。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
<style>
.activated {
color: red;
}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick" :class="{activated: isActivated}">Hello World</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
isActivated: false,
},
methods: {
handleDivClick: function() {
this.isActivated = !this.isActivated
}
}
})
</script>
</body>
</html>
class数组绑定
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
<style>
.activated {
color: red;
}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick" :class="[activated]">Hello World</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
activated: "",
},
methods: {
handleDivClick: function() {
this.activated = this.activated === 'activated' ? "" : "activated"
}
}
})
</script>
</body>
</html>
可以多个元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
<style>
.activated {
color: red;
}
</style>
</head>
<body>
<div id="app">
<div @click="handleDivClick" :class="[activated, activatedOne]">Hello World</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
activated: "",
activatedOne: 'activated-one',
},
methods: {
handleDivClick: function() {
this.activated = this.activated === 'activated' ? "" : "activated"
}
}
})
</script>
</body>
</html>
样式绑定
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
</head>
<body>
<div id="app">
<div :style="styleObj" @click="handleDivClick">Hello World</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
styleObj: {
color: "",
}
},
methods: {
handleDivClick: function() {
this.styleObj.color = this.styleObj.color === "" ? "red" : ""
}
}
})
</script>
</body>
</html>
可以多个元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
</head>
<body>
<div id="app">
<div :style="[styleObj, {fontSize: '20px'}]" @click="handleDivClick">Hello World</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
styleObj: {
color: "",
}
},
methods: {
handleDivClick: function() {
this.styleObj.color = this.styleObj.color === "" ? "red" : ""
}
}
})
</script>
</body>
</html>