Vue动态排序onclick by复选框选择

时间:2020-09-21 07:27:42

标签: javascript vue.js frontend web-frontend

我想让用户单击表时,复选框将更改属性,数据将被排序并动态显示。

<div id="app">
<table class="table table-hover">
  <tr>
    <th></th>
    <th></th>
    <th>Name</th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    <th>Value</th>
  </tr>
  <tr v-for="(item, index) in sortedData()" @click="item.selected = !item.selected">
    <td>
        <div class="p-20" style="padding-left: 20%;">
          <input type="checkbox" v-bind:id="[ item.id ]" v-model="item.selected">
        </div>
    </td>
    <td class="p-0 text-center">{{ index + 1 }}</td>
    <td>{{ item.id }}</td>
    <td class="align-middle"></td>
    <td></td>
    <td></td>
    <td></td>
    <td>{{ item.value }}  </td>
  </tr>

  </table>
</div>
<script>
var app = new Vue({
    el: "#app",
  data: function() {
    return {
        calculated: {
            "object1": {
            "selected": false,
            "value": 1
          },
          "object2": {
            "selected": false,
            "value": 20
          },
          "object3": {
            "selected": false,
            "value": 4
          },
          "object4": {
            "selected": false,
            "value": 24
          },
          "object5": {
            "selected": false,
            "value": 6
          },
          "object6": {
            "selected": false,
            "value": 0.26
          },
          "object7": {
            "selected": true,
            "value": 1.52
          },
          "object8": {
            "selected": false,
            "value": 0.54
          },
          "object9": {
            "selected": false,
            "value": 4.27
          }
        },
      }
  },
  methods: {
    sortedData: function() {
      let calculatedArray = []

      console.log(1)
      for (const [key, value] of Object.entries(this.calculated)) {
        calculatedArray.push({
          id: key,
          ...value
        })
      }

      if(calculatedArray) {
        return calculatedArray.sort(function(a, b) {
          return b.selected - a.selected
        })
      } else {
        return []
      }
    }
  }
})
</script>

我做错了,对我想要的没有用。

如果我在v-for中将“ selectedData”更改为“ calculated”,则复选框属性会通过单击更改, 但是数据未在表中排序。

0 个答案:

没有答案