[Vuejs]-Is there a way to force Vue to prefer the inherited class?

0πŸ‘

In my opinion, you have two options:

  1. for alignment, color, and … you can define props with the default classname values:
props: {
  alignment: 'start',
  // other props
},

and bind these props to the CSS class and use these there.

  1. You can use vue directives:
Vue.directive('tailwind', {
  bind: function(el, binding, vnode) {
    let currentClasses = el.classList;
    for (let i = 0; i < currentClasses.length; i++) {
      let className = currentClasses[i];
      if (className.startsWith('text-') || className.startsWith('justify-') || className.startsWith('font-')) {
        el.classList.remove(className);
      }
    }
  },
  update: function(el, binding, vnode) {
     let newClasses = binding.value.split(' ');
    for (let i = 0; i < newClasses.length; i++) {
      let className = newClasses[i];
      if (className.startsWith('text-') || className.startsWith('justify-') || className.startsWith('font-')) {
        el.classList.add(className);
      }
    }
  }
});

And you can use it in this way:

<button v-tailwind="class" class="text-sm font-roboto justify-center text-red-500">
  <slot></slot>
</button>

<MyButton class="justify-start text-gray-100">click me</MyButton>

0πŸ‘

I finally managed to do it by using a 3rd party library tailwind-merge

<template>
    <button :class="buttonClass">
        <slot></slot>
        <i class="text-base text-gray-400 font-normal">
        class="{{ buttonClass }}"</i>
    </button>
</template>

<script setup lang="ts">
    import { computed, useAttrs } from 'vue'
    import { twMerge } from 'tailwind-merge'

    const attrs = useAttrs()

    const buttonClass = computed(() => {
        return twMerge('font-bold text-3xl justify-center text-red-500 ', attrs.class)
    })
</script>

<script lang="ts">
    export default {
        inheritAttrs: false
    }
</script>

Leave a comment