How to put json variable directly into DIV Class

I need to change the color of a div element by a number that I assign in the script section. I am using Nuxtjs and tailwind.

This is the code what I want to work but sadly it doesn’t. Anyone knows another way to get to the same result?

<template>
<div class = "bg-[ "{{color}}" ]">
</div>
</template>

<script>
let color = 12345
</script>

So I am wondering is there a way to put a json Variable directly into the div class?

You can achieve this by using Vue’s :class binding or :style binding in Nuxt.js to dynamically apply a color based on a JavaScript variable. Since Tailwind CSS classes don’t accept dynamic values directly in the way you’ve written, you should use inline styles for this scenario. Here’s how you can do it:

Using Inline Styles

You can set the background color directly in the style attribute:

<template>
  <div :style="{ backgroundColor: `#${color}` }" class="h-64 w-full">
    <!-- Your content here -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      color: '12345' // Ensure this is a valid hex code (like '123456')
    };
  }
};
</script>

<style scoped>
/* Additional styles if necessary */
</style>

Explanation

  1. Dynamic Style Binding: The :style directive allows you to bind inline styles. Here, we are dynamically setting the backgroundColor using a template literal.
  2. Valid Hex Code: Make sure the color variable is a valid hex color code. If you’re using just numbers, they need to be formatted correctly (e.g., ‘123456’).
  3. Class for Height/Width: You can use Tailwind classes like h-64 w-full to define the height and width of your div.

This approach will dynamically change the background color of the div based on the value assigned to color.