如何使用 Vue 3 更改 div 的背景颜色?

How to change background color of a div using Vue 3?

我在模板中有以下行:

    <div class="card" @click="!state.clicked" :style="state.style">

在脚本中这段代码:

<script lang="ts">
import { ref, computed, reactive } from "vue";

export default {
  name: "Card",

  setup() {
    const state = reactive({
      clicked: false,
      style: computed(() => {
        backgroundColor: state.clicked ? "red" : "white";
      })
    });

    return {
      state
    };
  }
};
</script>

但是我的颜色没有变。我点击的标志正确切换,但我无法应用背景颜色。

不确定这是反应性问题还是我设置背景颜色的方式。

有什么想法吗?

您的计算属性没有 return 任何东西,return 没有任何东西意味着它自动 return 未定义。将其括在括号中

  style: computed(() => ({
    backgroundColor: state.clicked ? "red" : "white"
  }))