Say you want to apply the class background-dark
to an element, if the isDark
prop is true, and otherwise add the background-light
.
假设如果isDark
为true,则想将class background-dark
类应用于元素,否则添加background-light
。
How would you do that in Vue?
您将如何在Vue中做到这一点?
Use :class="[ isDark ? 'background-dark' : 'background-light' ]"
使用:class="[ isDark ? 'background-dark' : 'background-light' ]"
Here’s an example:
这是一个例子:
<template>
<div :class="[ isDark ? 'background-dark' : 'background-light' ]">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
props: {
isDark: Boolean
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.background-dark {
background-color: #000;
}
.background-light {
background-color: #fff;
}
</style>
(many thanks to Adam Wathan for suggesting this to me on the Tailwind Slack)
(非常感谢Adam Wathan在Tailwind Slack上向我建议这一点)