Class 与 Style 绑定
操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind
处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind
用于 class
和 style
时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
一、类名的绑定
1. vue中如何给dom添加类名?
(1)直接在DOM上绑定类名
eg:
<head>
<style>
.size {
width: 100px;
height: 100px;
}
.bg_color {
background: red;
}
</style>
</head>
<body>
<div id="app">
<h3> vue中类名添加第一种 </h3>
<p class="size bg_color"></p>
</div>
</body>
(2)vue中类名绑定 - 对象形式
目的: dom身上属性class 要和 数据绑定
解决方法:v-bind
数据中key,我们起的和绑定的对象中的key一样,但是这两个东西不一样。
格式: v-bind:class = "{ 属性: boolean }"
格式: v-bind:class = "{ [data]: boolean }"
eg:
<head>
<style>
.size {
width: 100px;
height: 100px;
}
.bg_color {
background: red;
}
</style>
</head>
<body>
<div id="app">
<h3> vue中类名添加第二种 - 对象的形式</h3>
<p :class="{ size: true,bg_color: false }"></p>
<p :class="{ size: true, bg_color: true }"></p>
<p :class="{ [s]: true, [bg_color]: true }"></p>
<p :class="{ [s]: 5>3?true: false, [bg_color]: true }"></p>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
s: 'size',
bg_color: 'bg_color',
}
})
</script>
(3)vue中类名绑定的形式 - 数组的形式(推荐)
格式: v-bind:class = "[ 数据 ]"
eg:
<head>
<style>
.size {
width: 100px;
height: 100px;
}
.bg_color {
background: red;
}
</style>
</head>
<body>
<div id="app">
<h3> vue中类名添加的第三种形式 - 数组形式( 推荐 )</h3>
<p :class="['size','bg_color']"></p>
<p :class="[ s, bg_color ]"></p>
<p :class="[ flag? s:'box', bg_color]"></p>
<!-- v-bind:class 指令也可以与普通的 class 属性共存。 -->
<p :class="[ flag? s:'box', bg_color]" class="yyb"></p>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
s: 'size',
bg_color: 'bg_color',
flag: true
}
})
</script>
2.类名绑定不会覆盖原先的类名
3.为什么要绑定类名?
指令是用来操作dom
目的: 为了将来通过数据来操作类名,类名操作dom
二、样式的绑定
格式:v-bind: style = " "
1.对象的形式
eg:
<body>
<div id="app">
<h3> style - 对象形式 </h3>
<p :style="{ width: size.width,height: size.height,background: 'red'}"></p>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
size: {
width: '100px',
height: '100px'
},
bg: {
background: 'purple'
}
}
})
</script>
2.数组的形式
eg:
<body>
<h3> style - 数组的形式 </h3>
<p :style="[ { width: '100px',background: 'blue'},{ height: '100px' } ]"></p>
<p :style="[ size,bg ]"></p>
</body>
<script>
new Vue({
el: '#app',
data: {
size: {
width: '100px',
height: '100px'
},
bg: {
background: 'purple'
}
}
})
</script>