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

Viewed 909

I have this following line inside the template:

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

And inside the script this code:

<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>

But my color doesn't change. My clicked flag is toggling correctly, but I just can't applied the background color.

Not sure if this is a reactivity issue or just the way I set the background color.

Any ideas ?

1 Answers

Your computed propertie doesnt return anything and returning nothing means it automatically returns undefined. Wrap it in parenthesis

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