!DOCTYPE htmlhtml lang=zh-CNhead meta charset=UTF-8 meta name=viewport content=width=device-width initial-scale=10 user-scalable=0 meta http-equiv=X-UA-Compatible content=ie=edge titleDocu
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 导包 -->
<script src="./vue.js"></script>
<style>
div>div {
width: 100px;
height: 100px;
border: 1px solid #000;
margin-top: 20px;
}
<pre><code> .red-box {
background-color: red;
}
.blue-box {
background-color: blue;
}
.greenBorder {
border: 10px solid green;
}
</style>
</code></pre>
</head>
<body>
<pre><code><!-- HTML结构 -->
<div id="app">
<!-- 本小节内容:Vue设置元素CSS样式的3种方式 -->
<!-- v-bind:class="{ '类名': bool, '类名': bool ......}"
如果值为true 该类样式就会被应用在元素身上, false则不会
注意点:如果类名有 - ,则需要使用引号包起来
-->
<button @click="changeClass">切换样式</button>
<div :class="{ 'red-box': flag, 'blue-box': !flag }"></div>
<hr>
<!-- v-bind:style="{ 属性名1: 属性值1, 属性名2: 属性值2 ...... }"
使用对象的形式,为元素动态设置样式
-->
<div :style="{ width: width, height: height, backgroundColor: bgc }"></div>
<!-- :class 和 :style 可以同时使用 -->
<div :class="{ greenBorder: true }" :style="{ width: '300px', height: '300px' }"></div>
</div>
<script>
/* 创建vue实例 */
let app = new Vue({
//el:挂载点
el: '#app',
//data: 要渲染的数据
data: {
flag:true,
width:'200px',
height:'200px',
bgc:'green'
},
methods: {
changeClass(){
this.flag = !this.flag;
}
},
})
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/bMk7 著作权归作者所有。请勿转载和采集!