·
1 min read

Vue Tip: Share Styling Using Wrapper Components

Vue Tip: Share Styling Using Wrapper Components Image

Often, you'll want to apply the same styling for Vue components. Instead of defining the class over and over again, you can include the styling within a wrapper component. Let's take a look at a simple example:

Component.vue
<template> <div class="bg-red-500"> <slot /> </div> </template>

Let's move this styling to a wrapper component:

Wrapper.vue
<template> <Wrapper> <slot /> </Wrapper> </template>

If you are using Tailwind and have a lot of classes, this can make your code cleaner and more maintainable.

This approach is also useful to provide scoped styling for your components. You can define the styles in the wrapper component and ensure that they don't leak to the parent component:

Wrapper.vue
<template> <Wrapper> <slot /> </Wrapper> </template> <style scoped> :deep(.inner-container::after) { @apply absolute top-0 -right-0.5 h-full pointer-events-none bg-gray-200 content-empty z-1; mask-image: linear-gradient(to right, transparent, black); } </style>