[Vuejs]-Vue class binding, better syntax?

1👍

Another solutions it’s to create a computed property where you list your classes and the condition to activate it, if the condition you write for one determinate class it true vuejs add this class to your element:

computed: {
  myClassName() {
    'section--margin-top': this.cartStep === 1 && this.cart.length >= 3,
    'section--full-screen section--centered': this.cartStep !== 1 || this.cart.length < 3
  } 

}

then in your pug code:

section.section(:class="myClassName")

1👍

I think a combination of computed properties and using template literal syntax would clean it up:

:class="`section--margin-top: ${marginTop}, section--full-screen section--centered: ${fullScreenCentered}`"

computed: {
    marginTop () {
        return this.cartStep === 1 && this.cart.length >= 3
    },
    fullScreenCentered () {
        return this.cartStep !== 1 || this.cart.length < 3
    }
}

I’m not familiar with pug so hope this translates properly.

0👍

So there are 4 approaches to consider:

  1. Object Syntax – { 'a': true, 'b': false, 'c': true } => a c
  2. Array Syntax – ['a', false ? 'b' : '', 'c'] => a c
  3. Mixed Syntax – ['a', { 'b': false, 'c': true }] => a c
  4. String Syntax – true ? 'a c' : 'b' => a c

And the last can work neatly here as the 2 conditions in the example are mutex:

:class="largeCart ? 'section--margin-top' : 'section--full-screen section--centered'"

With the following computed:

computed: {
    largeCart: (vm) => vm.cartStep === 1 && vm.cart.length >= 3,
}

Best pick a name that describes the scenario and not the resulting style.

Leave a comment