操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是 attribute,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
v-bind:class 一个对象,以动态地切换 class:
<div v-bind:class="{ active: isActive }"></div>
你可以在对象中传入更多字段来动态切换多个 class
<div
class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
给大家看一下我做的示例吧
<!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">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
<style>
.hide{
display: none;
}
</style>
</head>
<body>
<!-- v-bind:class 绑定class属性 -->
<div id="vuediv">
<div class="defaultClass" v-bind:class="classObj">洛洛大芳</div>
</div>
</body>
<script>
var vm=new Vue({
el:"#vuediv",
data() {
return {
// isHide:false,
// haserror:false
classObj:{
isHide:false,
haserror:false
}
}
},
})
</script>
</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">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="vuediv">
<div v-bind:style="[ArrayA,ArrayB]">洛洛大芳</div>
</div>
</body>
<script>
var vm=new Vue({
el:"#vuediv",
data() {
return {
ArrayA:{
width:'100px',
height:'40px'
},
ArrayB:{
"background-color":'red',
},
}
}
})
</script>
</html>
除了以上两种方式还有对象的形式绑定class属性
<!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">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="vuediv">
<div v-bind:style="styleObj">洛洛大芳</div>
</div>
</body>
<script>
var vm=new Vue({
el:"#vuediv",
data() {
return {
styleObj:{
width:'100px',
height:'40px',
'background-color':"red"
}
}
},
})
</script>
</html>
差不多就这些了吧,好好学习天天向上