我可以使用计算属性有条件地设置表格行的样式吗?

时间:2019-06-18 19:44:33

标签: javascript vue.js

我正在呈现一个用户表,我希望仅针对当前用户突出显示整个行。

我认为最简单的方法是通过计算属性,但是我无法使其正常工作。

在下面的注释中的代码是我在想的,但不会呈现。我只想要当前用户“ nathan”上的粉红色突出显示。

new Vue({
  el: '#app',
  data: {
    currentUser: 'nathan',
    users: [{
        name: "nathan",
        email: "nathan@gmail.com"
      },
      {
        name: "sally",
        email: "sally@gmail.com"
      },
      {
        name: "joe",
        email: "joe@gmail.com"
      }
    ],
  },
  computed: {
    styles: function(user) {
      let height = 100

      // something like this?
      // if(user === currentUser)
      if (user) {
        return {
          'background-color': 'pink'
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <tr v-for="user in users">
      <td v-bind:style="styles">{{ user.name }}</td>
      <td v-bind:style="styles">{{ user.email }}</td>
    </tr>
  </table>
</div>

1 个答案:

答案 0 :(得分:2)

您无法将参数传递给计算属性,因此不会填写user参数。

您可以根据需要创建一个类并将其添加到行中。

new Vue({
  el: '#app',
  data: {
    currentUser: 'nathan',
    users: [{
        name: "nathan",
        email: "nathan@gmail.com"
      },
      {
        name: "sally",
        email: "sally@gmail.com"
      },
      {
        name: "joe",
        email: "joe@gmail.com"
      }
    ],
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <tr v-for="user in users" :class="{'current-user' : user.name === currentUser}">
      <td>{{ user.name }}</td>
      <td>{{ user.email }}</td>
    </tr>
  </table>
</div>

<style>
  tr.current-user {
    background-color: pink;
  }
</style>

相关问题