【问题标题】:How to sort li's in reverse如何对 li 进行反向排序
【发布时间】:2017-06-05 22:34:06
【问题描述】:

我正在尝试对一个无序列表进行反向排序(vueJS 2.x),但我似乎无法找到任何关于过滤器的文档,例如 vue 1.x 中的过滤器(类似于 Angular 1做到了)

例如:

<li v-for="message in messages | orderBy 'name' -1">

但这不再起作用了。

我在这里尝试过使用计算属性:

computed: {
  reverse: function() {
    return this.messages.reverse();
  }
}

哪种 有效,但一旦通过页面上的表单提交了新消息,列表项就不会保持反转。

目标是始终保持列表项颠倒。

我尝试将反向函数附加到其他生命周期钩子,例如 beforeCreate 和 updated 但似乎没有任何效果。我错过了什么?

【问题讨论】:

  • 您需要在代码中订购的商品还是仅在 UI 上订购的商品?
  • 我想只是需要反转视图。正在从 Firebase 中提取消息数据

标签: javascript vuejs2 vue.js


【解决方案1】:

在 Vuejs 2 中确实没有过滤器...取而代之的是,您尝试使用 computed properties

<li v-for="message in sortedMessages">

然后:

computed: {
  sortedMessages: function() {
    return this.messages.slice().sort(function(message1, message2) {
        var name1 = message1.name.toLowerCase();
        var name2 = message2.name.toLowerCase();
        if(name1 < name2) return 1;
        if(name1 > name1) return -1;
        return 0;
    })
  }
}

希望这会有所帮助!

【讨论】:

  • 这将在无限循环中结束,因为.sort() 具有破坏性。不过,您可以使用this.messages.slice().sort(...) 轻松绕过它。
  • 好点 - 感谢您指出。我修改了答案。
【解决方案2】:

在 vueJS 2.x 文档的迁移部分,there is a note on replacing the orderBy filter

正如它所提到的,您应该能够使用类似lodash's orderBy 的函数,例如:

<li v-for="message in Orderedmessages">

computed: {
  Orderedmessages: function () {
    return _.orderBy(this.messages, ['name'], ['desc'])
  }

【讨论】:

    【解决方案3】:

    如果您只需要在 UI 中对列表进行排序,那么使用 CSS,您不再需要在模型中对其进行排序。

    对于垂直列表:

    ul{
        display: flex;
        flex-direction: column-reverse;
    }
    

    对于水平列表:

    ul{
        display: flex;
        flex-direction: row-reverse;
    }
    

    【讨论】:

    • 这有很多副作用。屏幕阅读器仍会以 DOM 顺序阅读它。此外,您将无法创建一个好的测试来查看事情是否真的反转了。
    【解决方案4】:

    这里要小心,因为Array.reverse 具有破坏性,会导致无限循环。当您尝试使用Array.sort 时,您也会遇到同样的情况。你可以这样做,而不是你所拥有的,因为你将使用副本:

    computed: {
      reverse: function() {
        return this.messages.slice().reverse()
      },
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多