The first style binding method: :class
object binding
<body>
<div id="app">
<div @click="handleClick" :class="{active: isActive}">Click Me To Change Color</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
isActive: false
},
methods: {
handleClick() {
}
}
});
</script>
</body>
In this way, the default div class is not available. The effect is as follows.
Let’s modify the method of the click event handleClick: In
this way, we can switch the class name of the div when the div is clicked, as follows:
So now just add an active style style. Make the effect of clicking to switch the div style
Complete code:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./vue.js"></script>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<div id="app">
<div @click="handleClick" :class="{active: isActive}" onselectstart="return false">Click Me To Change Color</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
isActive: false
},
methods: {
handleClick() {
this.isActive = !this.isActive
}
}
});
</script>
</body>
</html>
The second way of style binding: :class
array binding
Effect: After
clicking:
the third way of style binding: :style
object binding:
the third way of style binding: :style
array binding:
<body>
<div id="app">
<div @click="handleClick" :style="[styleObj1,styleObj2]" onselectstart="return false">Click Me To Change Color
</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
styleObj1: {
color: 'black',
backgroundColor: 'yellow'
},
styleObj2: {
border: '2px dashed slateblue'
}
},
methods: {
handleClick() {
this.styleObj1.color = this.styleObj1.color === 'black' ? 'yellow' : 'black'
this.styleObj1.backgroundColor = this.styleObj1.backgroundColor === 'yellow' ? '#4169E1' : 'yellow'
}
}
});
</script>
</body>