vue的table表格,控制行的样式颜色变化

可以使用Vue的条件渲染和动态类绑定来控制表格行元素的样式。

首先,在你的表格上设置一个`class`,比如`table-row`。然后,在`v-for`循环渲染每一行数据的时候,使用v-bind指令动态绑定样式类,使符合查询条件的行添加一个灰色的样式类,比如`gray-row`。如下面的示例代码:

```html
<template>
  <div>
    <label for="search-text">Search:</label>
    <input id="search-text" v-model="searchText" type="text">
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="person in filteredPeople" :class="{ table-row: true, gray-row: shouldGrayRow(person) }">
          <td>{
         
  { person.name }}</td>
          <td>{
         
  { person.age }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      people: [
        { name: Alice, age: 25 },
        { name: Bob, age: 30 },
        { name: Charlie, age: 35 },
        { name: David, age: 40 }
      ],
      searchText: 
    }
  },
  computed: {
    filteredPeople() {
      return this.people.filter(person => {
        return person.name.toLowerCase().includes(this.searchText.toLowerCase())
      })
    }
  },
  methods: {
    shouldGrayRow(person) {
      return person.age >= 30
    }
  }
}
</script>

<style>
.gray-row {
  background-color: #f1f1f1;
}
</style>
```

在这个例子中,我们使用`shouldGrayRow`方法来判断当前行是否符合灰化条件(比如年龄是否大于等于30岁),并在`v-bind:class`指令中动态绑定样式类。`table-row`样式类用于定义表格的默认样式,`gray-row`样式类用于定义灰化样式。你可以根据自己的需求修改类名和样式。

需要注意的是,当你改变搜索关键字时,computed属性会重新计算,会重新为每行数据绑定样式类,因此灰化样式会自动添加或移除。

经验分享 程序员 微信小程序 职场和发展