I use a dynamic class in Vue 3.
// Within a loop
<div v-for="(item, index) in store.state.data" :key="`data-${index}`">
<!-- I want to send item as an argument -->
<div :class="myComputed"></div>
</div>
const myComputed = computed(() => {
const number = 500;
return `bg-red-${number}`;
});
So far so good.
Now I want to send a variable to my computed property to have the class dynamic. By design Vue computed properties does not take an argument. Functions do, but when making it a function it's no longer reactive.
How can I solve it?
I recommend to make a computed property based on that store data by adding a field that contains the color :
const myData= computed(() => {
return store.state.data.map(item=>{
return {...item,bgColor:`bg-red-${item.number}`};
})
});
then loop through that property :
<div v-for="(item, index) in myData" :key="`data-${index}`">
<div :class="item.bgColor"></div>
</div>
in Tailwindcss the string concatenation is not recommended because the purge css will remove that classes. learn more