是否可以将参数传递给用于 class 和样式绑定的计算 属性?

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

我使用一组旅行者(例如 [2,0,0] => 2 名成人、0 名青少年、0 名儿童)来构建我的模板

<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>

我想在 template 中实现如此多的逻辑是不好的做法,而且看起来真的很尴尬。相反,我想将 class and style bindings 与计算的 属性.

一起使用
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)
    }
}

但是如何访问 v-fori?我可以将它作为参数传递吗?还是有其他更好的解决方案?

提前致谢!

如果你需要参数,那么你想写一个方法,而不是计算的属性.

<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)
    }
  }
}