Javascript is required
·
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
1<template>
2  <div class="bg-red-500">
3    <slot />
4  </div>
5</template>

Let's move this styling to a wrapper component:

Wrapper.vue
1<template>
2  <Wrapper>
3    <slot />
4  </Wrapper>
5</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
1<template>
2  <Wrapper>
3    <slot />
4  </Wrapper>
5</template>
6
7<style scoped>
8:deep(.inner-container::after) {
9  @apply absolute top-0 -right-0.5 h-full pointer-events-none bg-gray-200 content-empty z-1;
10  mask-image: linear-gradient(to right, transparent, black);
11}
12</style>

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.