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
Dynamic Style Binding: The :style directive allows you to bind inline styles. Here, we are dynamically setting the backgroundColor using a template literal.
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’).
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.