如何使用Vue动态应用类

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上向我建议这一点)

翻译自: https://flaviocopes.com/vue-apply-class-dynamically/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值