动态class
目标
用v-bind给标签class设置动态的值
语法
● 格式1:<标签 :class="变量" />
● 格式2:<标签 :class="{类名1: 布尔值, 类名2: 布尔值}" />
○ 如果布尔值为true,就添加对应的类名
说明:可以和静态class共存
<style>
#app{width:500px;margin:50px auto;border:3px solid red;}
.box{
border:3px solid black;
margin:5px;
}
.bg-blue{
background-color: blue;
}
.bg-green{
background-color: green;
}
.fs20{font-size:20px;}
.tr{text-align: right;}
</style>
</head>
<body>
<div id="app">
<h3 class="title">v-bind-绑定class</h3>
<!-- 元素自有class和v-bind绑定的class会协同工作,一起生效 -->
<div class="box" v-bind:class="cla ? 'bg-blue': 'bg-green'">
1. 三元表达式
</div>
<!-- 如果对象中的属性值是true,
则把对象中的属性名添加到类名中 -->
<div class="box" :class="claObj">
2. 绑定对象
</div>
<!-- 数组中元素是字符串,
它会把所有的元素全添加到class中 -->
<div class="box" :class="claArr">
3. 绑定数组
</div>
<button @click="hAddClass">补充一个class</button>
</div>
<script>
// v-bind 是用来动态绑定元素的属性,而class也是元素的属性
// 目标: 可以通过动绑定class来控制样式 。
// 方式:
// 1. 三元表达式
// 2. 绑定对象
// 3. 绑定数组
const vm = new Vue({
el: "#app",
// el: document.getElementById("app"),
data: {
cla: false,
claObj: {
fs20: true,
tr: true
},
claArr:['fs20','tr', 'abc']
},
methods: {
hAddClass () {
// 向数组中添加一个类 'c-red'
this.claArr.push('c-red')
}
}
})
</script>
小结
就是把类名保存在vue变量中赋予给标签
动态style
目标
给标签动态设置style的值
语法
<标签 :style="{css属性名: 值}" />
1. 可以和静态style共存
2. 样式中带-属性写成小驼峰
<div id="app">
<h3 class="title">v-bind-绑定style</h3>
<!-- 把对象的属性名和属性值直接设置到style中 -->
<div class="box" :style="styleObj">
1. 绑定对象
</div>
<!-- 把数组中的每一个元素(对象),取出来,组成style -->
<div class="box" :style="styleArr">