Search code examples
vue.jsbindingcomputed-properties

Is it possible to pass an argument to a computed property that is used for class and style bindings?


I have an array of travelers (e.g. [2,0,0] => 2 adults, 0 teens, 0 childs) that I use to build my template

<div v-for="(person, i) in travelers" :key="i" class="uk-width-1-3@m">
    <div class="uk-card-body">
        <button
            class="uk-button uk-button-small uk-margin-right"
            @click="changeTravelers({index: i, value: travelers[i]-1})"
            :class="{
                 'uk-disabled uk-button-default': travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
                 'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
             }"
        >-</button>
        <span>{{ travelers[i] }}</span>
        <button
            class="uk-button uk-button-small uk-margin-left"
            @click="changeTravelers({index: i, value: travelers[i]+1})"
            :class="{'uk-disabled uk-button-default': curOcc >= maxOcc, 'uk-button-primary': curOcc < maxOcc}"
        >+</button>
    </div>
</div>

I guess it's bad practice to implement so much logic into the template and it look's really awkward. Instead I want to use class and style bindings with an computed property.

styleMinusButton() {
    return {
        'uk-disabled uk-button-default': this.travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
        'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
    }
}

But how do I access the i of the v-for? Can I pass it as an argument? Or is there a different and better solution?

Thanks in advance!


Solution

  • If you need arguments then you want to write a method, not a computed property.

    <button :class="styleMinusButton(i)">...</button>
    
    methods: {
      styleMinusButton(i) {
        const { travelers, curOcc, minOcc } = this
        return {
          'uk-disabled uk-button-default': travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
          'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
        }
      }
    }