2

I use a dynamic class in Vue 3.

In template

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

In setup()

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.