Changing the utilities/values in a class of a bootstrap button

Viewed 23

I have this code:

<b-button
id="search-button"
size="md"
class="mt-1 w-100"
type="submit"
@click="someEvent()"
>Example
</b-button

Let's say I call someEvent() and in the script I want to change the value of class="mt-1 w-100" to class="mt-1 w-90"

One workaround for this is to define a style in the b-button and do document.getElementById("search-button").style.width = "90px"; in the script, but that's not what I'm looking for.

The question is, how do I access the class utilities/values and change them directly from the script.

2 Answers

I believe this is what you are looking for?

<b-button
  id="search-button"
  size="md"
  class="mt-1"
  :class="hasClicked ? 'w-90' : 'w-100'
  type="submit"
  @click="hasClicked = !hasClicked"
>
Example
</b-button>

define variable hasClicked in either ref (composition API) or data block (options API).

For example

data(){ 
  hasClicked: false
}

basically you use class binding method (https://vuejs.org/guide/essentials/class-and-style.html) along with tenary operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)

You can achieve that by dynamic class binding concept. Instead of hard coding the value of class attribute, we can bind that dynamically based on the condition.

In <b-button> element :

Use :class="dynamicStyles" instead of class="mt-1 w-100"

In script :

data: {
  dynamicStyles: 'mt-1 w-100'
}

someEvent() {
  // based on some condition we can update the dynamicStyles.
  this.dynamicStyles = 'mt-1 w-90'
}
Related