V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gap
V2EX  ›  Vue.js

请问在 vue 2 中如何能在 v-for 对象情况下根据对象某个 key 来排序列表呢?

  •  
  •   gap · 2017-05-22 22:39:36 +08:00 · 3847 次点击
    这是一个创建于 2502 天前的主题,其中的信息可能已经有所发展或是发生改变。

    由于数据结构的原因,v-for 的是对象属性,每个属性又是一个对象,现在希望让列表按 order 这个属性进行排序,请问能做到吗?

    const objects = {
      prop1: { text: 'a', order: 3 },
      prop2: { text: 'c', order: 1 },
      prop3: { text: 'b', order: 2 },
    }
    <template v-for="(value, key) in objects">
      <div>{{ value.text }}</div>
    </template>
    

    希望的 output

    c
    b
    a
    
    4 条回复    2017-06-02 13:52:48 +08:00
    Biwood
        2
    Biwood  
       2017-05-22 22:52:43 +08:00
    手动给数据排序也不是什么麻烦事,新建一个数组,用 order 作为索引并赋值对应的值
    Sparetire
        3
    Sparetire  
       2017-05-23 08:23:37 +08:00 via Android
    用计算属性吧
    470326964
        4
    470326964  
       2017-06-02 13:52:48 +08:00
    计算属性返回值,然后拿返回值去遍历。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1711 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 16:40 · PVG 00:40 · LAX 09:40 · JFK 12:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.