<script setup lang="ts">
const props = defineProps({
px: {
type: String,
required: false,
},
bg: {
type: String,
default: 'transparent',
},
rounded: {
type: String,
default: 'none',
}
})
const classes = []
for (const [key, value] of Object.entries(props)) {
(value !== undefined) && classes.push(`${key}-${value}`)
}
</script>
<template>
<div : >
<slot></slot>
</div>
</template>
Because the props is reactive, so I think the DOM will finish rendering before script's process. How can I let the component wait for script's process? Thanks.
the classed has been added but it's reactive so they don't effect...
CodePudding user response:
Don't construct class names dynamically
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS
How to use dynamic class names in tailwindcss -> use dynamic class name in tailwindcss
<!-- wrong ❌ -->
<div ></div>
<!-- correct ✅ -->
<div ></div>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps({
pxClass: {
type: String,
required: false,
default: 'px-4'
},
bgClass: {
type: String,
default: 'bg-transparent',
},
roundedClass: {
type: String,
default: 'rouned-none',
}
});
const classes = computed(() => {
let result = [];
for (const [key, value] of Object.entries(props)) {
result.push(value)
}
return result;
})
</script>
<template>
<div : >
<slot></slot>
</div>
</template>
CodePudding user response:
This answer do have a really valid point of warning about dynamic classes. If you don't do that, you'll get your whole CSS payload bloated because Tailwind will not be able to generate only the needed utility classes.
Defeating the whole purpose of Tailwind. You can't have dynamic classes utility classes at the same time mainly.
Here is an approach on how to do dynamic stuff in Vue with Tailwind's classes if you prefer to have an Options API approach on how to solve things.
As of today, this mapping is still the official way to go (confirmed by founders on Github discussions).