如何使用Vue動態應用類別

學習如何在Vue中根據條件動態應用類別或其他類別。 假設您希望根據isDark屬性的值來將background-dark類別應用於元素上,如果它是true的話,否則添加background-light類別。 在Vue中,您該如何做到這一點? 使用 :class="[ isDark ? 'background-dark' : 'background-light' ]"。 以下是一個示例: <template> <div :class="[ isDark ? 'background-dark' : 'background-light' ]"> <h1>{{ msg }}</h1> </div> </template> <script> export default { props: { isDark: Boolean } } </script> <!-- 添加“scoped”屬性將CSS限制在此元件內部 --> <style scoped> .background-dark { background-color: #000; } .background-light { background-color: #fff; } </style> (非常感謝Adam Wathan在Tailwind Slack上提出這個建議)