一、简介
通过事件改变css样式,有两种方式,属性绑定和计算属性绑定。
二、案例
①、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- cdn是一种引入 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- 这里用link印入 -->
<link rel="stylesheet" href="styles.css">
<title>vue-cdn</title>
</head>
<body>
<div id="vue-app">
<h1>动态绑定样式 两种方式</h1>
<!-- <h2>示例1 属性绑定</h2> -->
<!-- click可以直接是一个表达式 -->
<!-- <div @click="mrChangeColor = !mrChangeColor" v-bind:class="{changeColor:mrChangeColor}">
<span>Hello</span>
</div> -->
<h2>示例2 计算属性绑定</h2>
<!-- 计算属性是确定它发生了变化,才会更新 -->
<!-- click可以直接是一个表达式 -->
<button @click="mrChangeColor = !mrChangeColor">改颜色</button>
<button @click="mrchangeLength = !mrchangeLength">改长度</button>
<div v-bind:class="compClasses">
<span>Hello</span>
</div>
</div>
</body>
<script src="app.js"></script>
</html>
②、app.js
new Vue({
el: "#vue-app",
data() {
return {
mrChangeColor: false,
mrchangeLength: false
};
},
methods: {},
computed: {
compClasses() {
//这里的ChangeColor一定要跟.CSS里的名字匹配上
return {
ChangeColor: this.mrChangeColor,
changeLength: this.mrchangeLength
}; //this.mrChangeColor才能找到那个值
}
}
})
③style.css
span {
background: red;
display: inline-block;
padding: 10px;
color: #fff;
margin: 10px 0;
}
.ChangeColor span {
background: green;
}
.changeLength span:after {
content: '小蒋';
margin-left: 10px;
}