有时候遇到某些内容需要根据用户需要切换是否加.class,我看到有很多地方用3元表达式来做切换,我想到一种既直观又简洁优雅的方式。
先看代码:
<script setup>
import { ref } from 'vue'
const isRed = ref(true)
</script>
<template>
<button @click="isRed = !isRed">切换</button>
<h1 :class="{isRed}">Vue is awesome!</h1>
</template>
<style>
.isRed{
color:red
}
</style>
isRed在style里是类属性名,在script里是布尔值。在template里会判断isRed,为true时就会加上类属性isRed,为false时不会加上类属性isRed,注意:class="{isRed}"的花括号不能漏写,漏了花括号就不会生效。