class 与 style 是 HTML 元素的属性,用于设置元素的样式,我们可以用 v-bind 来设置样式属性。
Vue.js v-bind 在处理 class 和 style 时, 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。
动态切换多个 class
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<style> .active { width: 100px; height: 100px; background: green;
} .text-danger { background: red;
}
</style>
</head>
<body>
<div id="app">
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
</div>
<script>
new Vue({ el: '#app', data: { isActive: true, hasError: true } }) </script>
</body>
</html>
text-danger 类背景颜色覆盖了 active 类的背景色.实际渲染后如下:
<div class="static active text-danger"></div>
将样式绑定到对象
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<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>
以上效果都是一样的,如下图:
computed 对象属性
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<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: { isActive: true, error: null }, computed: { classObject: function () { return { active: this.isActive && !this.error, 'text-danger': this.error && this.error.type === 'fatal', } } } }) </script>
</body>
</html>
效果为绿色。
数组语法[]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<style> .active { width: 100px; height: 100px; background: green;
} .text-danger { background: red;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="[activeClass, errorClass]"></div>
</div>
<script>
new Vue({ el: '#app', data: { activeClass: 'active', errorClass: 'text-danger' } }) </script>
</body>
</html>
效果为红色。
三元表达式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<style> .text-danger { width: 100px; height: 100px; background: red;
} .active { width: 100px; height: 100px; background: green;
}
</style>
</head>
<body>
<div id="app">
<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
</div>
<script>
new Vue({ el: '#app', data: { isActive: true, activeClass: 'active', errorClass: 'text-danger' } }) </script>
</body>
</html>
效果为绿色。