Vue之动态绑定CSS样式

demo.html

 <!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-html="http://www.w3.org/1999/xhtml"
xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Vue Demo</title>
<!--自选版本-->
<!--<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>-->
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生产环境版本,优化了尺寸和速度 -->
<!--<script src="https://cdn.jsdelivr.net/npm/vue"></script>-->
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="app">
<div>
<h2>动态绑定CSS样式</h2>
<div>
<h4>示例一</h4>
<div v-on:click="varChangeColor = !varChangeColor" v-bind:class="{changeColor:varChangeColor}">
<span>点击切换颜色</span>
</div> <hr>
<h4>示例二</h4>
<button v-on:click="varChangeColor = !varChangeColor">改变颜色</button>
<button v-on:click="varChangeLength = !varChangeLength">改变长度</button>
<button v-on:click="varChangeLength = !varChangeLength,varChangeColor = !varChangeColor">两者都改变</button>
<!--computed属性封装对象-->
<div v-bind:class="computedClass">
<span>测试内容</span>
</div>
</div> </div> </div>
<script src="app.js"></script> </body>
</html>

app.js

 var app = new Vue({
el: '#app',
data: {
varChangeColor: false,
varChangeLength: false,
},
methods: {}, computed: {
computedClass: function () {
return {
changeColor: this.varChangeColor,
changeLength: this.varChangeLength
}
},
}
})

style.css

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

截图:

Vue之动态绑定CSS样式

上一篇:巧用hover改变css样式和背景


下一篇:使用淘宝npm镜像