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>
效果為綠色。