简体   繁体   English

Vue 3 class 绑定是否需要内联变量?

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

Given the following HTML:给定以下 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 )?有没有办法将 class 绑定移出 HTML,因为它依赖于通过v-for循环( 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).文档提到能够 绑定计算属性,但我的理解是这些不接受 arguments (而且我无法让它以这种方式工作)。

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:如果您使用的是 Vue 2 或选项 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.一定要避免在方法中更改实例属性,但是读取是可以的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM