Are Vue 3 class bindings with variables required to be in-line?

Viewed 476

Given the following HTML:

<template v-for="(child, index) in group">
    <div :class="{'border-pink-700 bg-gray-100 ': selected === child.id}">
        <div>Container Content</div>
    </div>
</template>

Is there a way to move the class binding out of the HTML, given that it relies on a condition passed via the v-for loop (child.id)?

The docs mention being able to bind computed properties, but my understanding is that these don't accept arguments (and I haven't been able to get it to work that way).

1 Answers

You can use a method and pass the item to the method:

<div :class="classes(child)">
setup() {
  ...
  const classes = (child) => {
    return {
      'border-pink-700 bg-gray-100': selected.value === child.id
    }
  } 
    
  return {
    ...
    selected,
    classes
  }
}

If you were using Vue 2 or the Options API:

methods: {
  classes(child) {
    return {
      'border-pink-700 bg-gray-100': this.selected === child.id
    }
  }
}

Be sure to avoid changing instance properties in the method, but reading is ok.

Related