元素 UI 对 table 中的值排序无效

Element UI sort values in a table not working

我正在尝试制作一个简单的排序功能,但它似乎不起作用。

var Main = {
  data() {
    return {
      tableData: [{
        value: '1.799,37',
        name: 'Tom 3'
      }, {
        value: '2.183,88',
        name: 'Tom 2'
      }, {
        value: '3.837,05',
        name: 'Tom 4'
      }, {
        value: '769,8',
        name: 'Tom 6'
      }, {
        value: '111,8',
        name: 'Tom 6'
      }, {
        value: '999,8',
        name: 'Tom 6'
      }]
    }
  },
  methods: {
    test: function(a, b) {
      return a.value - b.value;
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/element-ui@1.3.4/lib/theme-default/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@1.3.4/lib/index.js"></script>
<div id="app">
  <template>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="value" label="Value" sortable :sort-method=test width="180"></el-table-column>
    <el-table-column prop="name" sortable label="Name" width="180"></el-table-column>
  </el-table>
</template>
</div>

在你的数组 tableData 中,每个对象都有一个 value 是一个字符串。 所以你的排序方法比较字符串。但在这里我认为你想按数字对它们进行排序。

您需要做的是像这样更新您的方法:

methods: {
  test: function(a, b) {
    return this.toFloat(a.value) - this.toFloat(b.value)
  },
  toFloat: function(num) {
    return parseFloat(num.replace('.','').replace(',','.'))
  }
}

注意 replace 是为了使您的字符串有效数字

var Main = {
  data() {
    return {
      tableData: [{
        value: '1.799,37',
        name: 'Tom 3'
      }, {
        value: '2.183,88',
        name: 'Tom 2'
      }, {
        value: '3.837,05',
        name: 'Tom 4'
      }, {
        value: '769,8',
        name: 'Tom 6'
      }, {
        value: '111,8',
        name: 'Tom 6'
      }, {
        value: '999,8',
        name: 'Tom 6'
      }]
    }
  },
  methods: {
    test: function(a, b) {
      return this.toFloat(a.value) - this.toFloat(b.value)
    },
    toFloat: function(num) {
      return parseFloat(num.replace('.','').replace(',','.'))
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/element-ui@1.3.4/lib/theme-default/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.0.11/lib/index.js"></script>
<div id="app">
  <template>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="value" label="Value" sortable :sort-method=test width="180"></el-table-column>
    <el-table-column prop="name" sortable label="Name" width="180"></el-table-column>
  </el-table>
</template>
</div>

 sortName(a,b) {
        if (a.name.toUpperCase() <  b.name.toUpperCase()) return -1;
       if (a.name.toUpperCase() > b.name.toUpperCase()) return 1;
       return 0;
 }