Vue.js orderBy无法正常使用大写和小写

时间:2016-04-02 00:49:06

标签: javascript vue.js

我正在使用Laravel 5.2 + Vuejs + Vueify处理应用程序,我在桌面上列出了一个对象数组,但我遇到了2个问题。

1。 orderBy以大写和小写分隔

orderBy以记录分隔,其中第一个字母是大写和小写!

2。过滤器领域的特价caracteres

在过滤器字段中键入“Á gua”找不到“Agua”结果,因为字母A上的重音突出并且我想忽略重音...这是可能的?

JS档案

<div class="container">
  <input type="text" v-model="textFilter" class="form-control" placeholder="Type to filter...">
</div>

<hr>

<div class="container">
  <div class="alert alert-info">Click at the TH to sort</div>
  <table class="table table-striped table-bordered">
    <thead>
      <tr>
        <th @click="sort('id')" style="cursor: pointer;">Id</th>
        <th @click="sort('name')" style="cursor: pointer;">Name</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="r in list | filterBy textFilter | pmlOrderBy sortProperty sortDirection">
        <td class="text-center" style="width:90px">{{ r.id }}</td>
        <td>{{ r.name }}</td>
      </tr>
    </tbody>
  </table>
</div>

HTML文件

{{1}}

JS Bin

====编辑====

泰勒和RainningChain帮助我吼叫,我们几乎到了那里!

我找到this article并更新了上面的代码和JS Bin,但现在的问题是:

  • 排序正确,但如果我尝试对其他列进行排序,请点击另一个TH进行制动。
  • 特殊的caracteres的问题仍然存在= /

任何?

谢谢!

1 个答案:

答案 0 :(得分:1)

为了实现这一目标,您必须创建自己的过滤器。

扩展Vue的orderBy过滤器,这将是解决您的两个问题的功能性解决方案。

// This was originally copied from the Vue source
// File: src/filters/array-filters.js
function orderByWords (arr, sortKey, reverse) {
  arr = convertArray(arr)
  if (!sortKey) {
    return arr
  }
  var order = (reverse && reverse < 0) ? -1 : 1
  // sort on a copy to avoid mutating original array
  return arr.slice().sort(function (a, b) {
    if (sortKey !== '$key') {
      if (isObject(a) && '$value' in a) a = a.$value
      if (isObject(b) && '$value' in b) b = b.$value
    }
    a = isObject(a) ? getPath(a, sortKey) : a
    b = isObject(b) ? getPath(b, sortKey) : b
    return a.localeCompare(b) * order
  })
}

过滤器的肉是这个片段: a.localeCompare(b)

String.prototype.localeCompare方法比较两个字符串,并根据初始字符串(a)是在比较字符串(b)之前还是之后返回一个整数值。

<强>更新

事实证明过滤器正在崩溃,因为Number.prototype.localeCompare不存在......谁知道?

因此,我们可以使用一点点类型转换技巧来实现这一点。

Vue.filter('pmlOrderBy', function (arr, sortKey, reverse) {
    if (!sortKey) {
        return arr;
    }
    var order = (reverse && reverse < 0) ? -1 : 1;

    // sort on a copy to avoid mutating original array
    return arr.slice().sort(function (a, b) {
        if (sortKey !== '$key') {
            if (Vue.util.isObject(a) && '$value' in a) a = a.$value;
            if (Vue.util.isObject(b) && '$value' in b) b = b.$value;
        }
        a = Vue.util.isObject(a) ? Vue.parsers.path.getPath(a, sortKey) : a;
        b = Vue.util.isObject(b) ? Vue.parsers.path.getPath(b, sortKey) : b;

        return (''+a).localeCompare((''+b)) * order;
    });
});

关键行是过滤器的最后一行。 (''+a).localeCompare会将a强制转换为String,然后调用localeCompare方法。