vue.js学习——样式绑定
这里主要是使用v-bind标签
直接贴代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
<style>
.active{
width:100px;
height:100px;
background:blue;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="{active:isactive}"></div>
</div>
<p id="info">
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
isactive:true
},
});
</script>
</body>
</html>
运行结果如下:
下面对代码进行解释:
<div v-bind:class="{active:isactive}"></div>
这里的active表示style里面的.active样式,isactive为它的属性值
isactive:true
在这里将active的属性值标为true,则表示显示此样式
拓展1 样式覆盖
若将上述代码进行修改后如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
<style>
.active{
width:100px;
height:100px;
background:blue;
}
.end{
background: red;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="{active:isactive, 'end':end1}"></div>
</div>
<p id="info">
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
isactive:true,
end1:true
},
});
</script>
</body>
</html>
则显示结果如下所示:
这是由于end类背景颜色覆盖掉了active类的颜色,同理,可以加第三个style来覆盖end类
拓展2 使用对象
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<style>
.active {
width: 100px;
height: 100px;
background: green;
}
.text-danger {
background: red;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="classObject"></div>
</div>
<script>
new Vue({
el: '#app',
data: {
classObject: {
active: true,
'text-danger': true
}
}
})
</script>
</body>
</html>
运行结果和上述相同
在这里将v-bind的class归为一个对象,然后在对象中进行样式的开关