0

I have this component with some dynamic classes but it looks a little messy and I can't seem to figure out if there's a better way to write it. The class binding in vue kind of confuses me.

I'm using pug btw, but the focus should be on the :class anyway

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

Should I be using a computed property? Or maybe the array syntax (which I can't quite wrap my head around)? Or...?

Thanks everyone for the help.

3 Answers 3

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")
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Yes this would definitely work on pug and it is for sure a little cleaner. Thanks
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.