如何使用Vue動態應用類別
學習如何在Vue中根據條件動態應用類別或其他類別。
假設您希望根據isDark屬性的值來將background-dark類別應用於元素上,如果它是true的話,否則添加background-light類別。
在Vue中,您該如何做到這一點?
使用 :class="[ isDark ? 'background-dark' : 'background-light' ]"。
以下是一個示例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | <template><div :class="[ isDark ? 'background-dark' : 'background-light' ]">
 <h1>{{ msg }}</h1>
 </div>
 </template>
 
 <script>
 export default {
 props: {
 isDark: Boolean
 }
 }
 </script>
 
 
 <style scoped>
 .background-dark {
 background-color: #000;
 }
 .background-light {
 background-color: #fff;
 }
 </style>
 
 | 
(非常感謝Adam Wathan在Tailwind Slack上提出這個建議)
tags: [“Vue”, “前端開發”, “Class綁定”]