Home > Net >  change button class or style based on its dynamic text (Vuejs)
change button class or style based on its dynamic text (Vuejs)

Time:12-03

I have v-for loop to create about 20 buttons. Every button text comes from the for loop.

I also have a function which returns a number inside the button text. All is working, but I want to change the class/background color of the text based on the function which takes as parameter from the for loop

      <v-btn v-for="(myDate, idx) in dateRange"  :key="idx"
        
        outlined
        color="indigo"
        
        >  
      {{myDate.toLocaleDateString("en-US")}} - ({{markIfThisDateHaveItems(myDate)}})
    </v-btn>

I like to set the class based on this function:

markIfThisDateHaveItems(myDate)

Is it possible?

CodePudding user response:

Yes, this is possible! First: Instead of having a List of Date in dateRang. Transform it to a list of object. We assume that "markIfThisDateHaveItems(date)" function returns a bool value In script:

dateRange: [
{
date : date1,
hasItems : markIfThisDateHaveItems(date1)
},
{
date : date2,
hasItems : markIfThisDateHaveItems(date2)
},
]

Now In Vue we update class accordingly of the hasItems value of each Object:

<v-btn v-for="(myDateObject, idx) in dateRange"  :key="idx"
        :
        outlined
        color="indigo"
        
        >  
      {{myDateObject.date.toLocaleDateString("en-US")}} - {{myDateObject.hasItems)}})
    </v-btn>

CodePudding user response:

Another way to easily accomplish this would be to define a button component and run your v-for loop over that component. Then pass down a prop as the result of your fn call. You would need to be careful with your prop logic in the button component such that you were not looking for a value that doesn't exist or a property of null for example. An easy fix, would be to use a v-if inside the button component itself to confirm that the result of your fn call (the button's prop) was available.

Something like this:

// Main

 <MyButton v-for="(myDate, idx) in dateRange"  :key="idx"
    :classes="yourFn(foo)"
 />

// MyButton

<template>
  <v-btn 
   v-if="classes"
   type="button" role="button"  color="indigo" :
  >
      {{myDate.toLocaleDateString("en-US")}} = - ({{markIfThisDateHaveItems(myDate)}})
  </v-btn>
</template

<script>
export default {
 name: 'MyButton',
 props: {
 classes: {
  type: [String, Array],
  required: false,
  default: null,
  }
}
</script>

I haven't tried binding a class to a fn output, I typically would use computed properties for this or a classObject (just a computed property concept), see docs already linked to you. I don't know if Vue will complain if you bind a prop to fn. Assume ok. Note that in the example, your button will not render unless your fn returns a valid string or array. Hope that helps. -Marcus

  • Related