Is it possible to instruct Vue to prioritize the inherited class over others?

I have a situation in my component where I need Vue to disregard the existing class and instead use the inherited class, but only if it is of the same type as the inherited class. Let me illustrate with an example:

Consider a button component like this

MyButton.vue

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

In my project, I want to use the MyButton component but override the classes justify-center and text-red-500 with my own, like so:

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

This should result in the following button being rendered:

<button class="text-sm font-roboto justify-center text-red-500 justify-start text-gray-100">
  click me
</button>

The issue arises when HTML prioritizes the class justify-center over justify-start. I wish for Vue to intelligently handle Tailwind classes, recognizing that if it originally had justify-center and now I provide justify-start, it should replace rather than add them both.

This behavior should extend to all Tailwind classes – replacing rather than adding original text-...., font, color, shadow, etc., classes with the new ones.

Therefore, the desired output would be:

<button class="text-sm font-roboto justify-start text-gray-100">
  click me
</button>

Answer №1

After much perseverance, I was able to achieve my goal with the help of an external tool called windtail-fusion

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

<script setup lang="ts">
    import { computed, useAttrs } from 'vue'
    import { windtailFusion } from 'windtail-fusion'

    const attrs = useAttrs()

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

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

Answer №2

From my perspective, you have two choices:

  1. When it comes to alignment, color, and so on, you can set props with the default classname values:
props: {
  alignment: 'start',
  // other props
},

Then link these props to the CSS class and apply them accordingly.

  1. Another option is to utilize 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);
      }
    }
  }
});

This directive can now be implemented as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to generate excel spreadsheets using a selection in Laravel?

In my system, I have implemented a radio group as a filter for my table which displays items as active, inactive, or both. Additionally, there is a button that allows users to export the table data into an Excel document. Currently, the export button downl ...

Vue app showcasing array items through search upon button pressing

As I delve into learning Vue Js, I've encountered a bit of confusion. My goal is to showcase array elements from a Rest API based on the specific ID being searched for. For example: within my Json File are various individuals with unique IDs, and when ...

Transforming an unordered list to function similarly to a select input

I am looking to style a ul list to function as a select form element. I have successfully populated a hidden input using my code. Now, I am trying to make the ul behave like a select input when either the keyboard or mouse is used. Previously, I had some ...

Can floating elements be disregarded by block elements?

According to W3C, the behavior of floating elements is such that: When a float is present, non-positioned block boxes that come before and after the float flow vertically as if the float doesn't exist. However, line boxes positioned next to the fl ...

An easy guide on implementing the if control statement within a Jinja2 embedded HTML document

Utilizing parsehub, I have successfully scraped a list of movie names and exported it to an html file using a python script. However, my intention is to only display titles that contain the word "The" by implementing an if statement. The code structure app ...

Ways to delete a tag with jQuery

Currently I'm struggling with hiding elements like delpc and picnam. Here is the structure of my code: <ul id="userpic" class="user pic"> <im class="pict"/> Picture preview </ul> <div id="showpicname"> <div id= ...

Unique symbols within HTML tags

Many times when the topic of HTML attributes is brought up, people are referring to the value of the attribute. However, I am interested in discussing the actual attributes themselves. Would you consider the following code snippet to be valid? <a href= ...

Presentation for a div's background image with the use of jQuery

My header contains a large div with text contents and boxes, along with a background image. Now I want to create a slideshow for this div's background. Does anyone know how to make a slideshow for a div's background image? I've searched ex ...

Can you explain how I can use AJAX in HTML to change the text of a link once it has been clicked on?

I have a link titled Save to Favorites. This link triggers an AJAX function when clicked, which updates the text of the link to say Remove from Favorites. Clicking it again changes it back to Save to Favorites. What code should I include in the link itsel ...

Fill the next Thursday with JavaScript

I'm having trouble updating the date for the upcoming Thursday using JavaScript. The current script works fine until the end of the month, but if it's the 25th of August, the output will be "Next Thursday - 8/32/2022". I need a more intelligent s ...

What are the best strategies for optimizing my CSS drop down menu to be both responsive and mobile-friendly?

I am struggling to make my current CSS and HTML menu fully responsive and mobile-friendly. I have researched solutions from other sources but have been unable to implement them successfully. I am seeking help in modifying my menu so that it adjusts to smal ...

Challenge with maintaining tab view data in Openui5

I am facing an issue with my application's tabs. Each tab renders data retrieved through ajax calls from the database. However, whenever I switch between tabs, the data gets refreshed each time. Is there a way to prevent this refreshing behavior and i ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Unforeseen outcomes arise when toggling expansion in JavaScript

I have a pop-out div at the top of my page that expands and closes on toggle. Also, when I toggle the pop-out div, it changes the top position of another div (a side pop-out menu). The issue is that the side pop-out menu should only appear when clicking ...

What steps can I take to ensure that the browser prints out a PDF copy of a webpage?

Imagine you have a website page saved as example.html, and also a printable file named example.pdf. Is there a way to prompt the browser to open and print example.pdf instead of example.html when users attempt to print? If this isn't achievable, how ...

Arranging buttons in a row with Bootstrap 5

Struggling to align the buttons on my webpage side by side in the center, I've tried two Bootstrap 5 classes but they're not achieving the desired look: https://gyazo.com/c23f2eade4614380aec547b11e61387a https://gyazo.com/e40a678b02c9f641f746b1c ...

The background image is not displaying properly within a <span> tag

I am attempting to show a smiley icon within a span tag that is nested inside a list item. Below is the code snippet: <p> It contains various tabs:{" "} <li> Home - Showcase and brief informati ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Expand the dimensions of the file upload field to make it taller and wider

I am trying to create a file upload field within a transparent div sized at 150px x 150px. The goal is for the file dialog box to pop up when any part of the div is clicked, allowing the user to select a file for upload. Despite my attempts, I haven't ...