vue 根据名称更改对象顺序_如何在Vue模板中对对象中的数据进行排序?

像这样的东西 . 在这里,我显然没有使用Vuex,但你可以使用Vuex getter . 如果您需要排序对象中的主题 id ,则可以将其添加到 Map 中 .

console.clear()

// topics:

// - [firebase-push-key]

// - title

// - text

// - ...

const topics = {

"1234":{

title: "Ziss one starts with Z",

text: "text1"

},

"2345":{

title: "M is for middle",

text: "text2"

},

"3456":{

title: "Alpha title",

text: "text3"

}

}

new Vue({

el:"#app",

data:{

topics

},

methods:{

sortProperty(prop){

return (a,b) => {

if (a[prop] < b[prop])

return -1;

if (a[prop] > b[prop])

return 1;

return 0;

}

}

},

computed:{

sortedTopics(){

return Object.keys(this.topics)

.map(t => {

this.$set(this.topics[t], 'key', t)

return this.topics[t]

})

.sort(this.sortProperty('title'))

}

}

})

{{topic}}

Edit

这是一个处理更新数据结构的示例 .

const topics = [{

"-Kmbspn0WYBlNXfmfVlR": {

"slug": "arne",

"title": "Arne"

}

}, {

"-KmbsqiG_9uXzRhHrnXZ": {

"slug": "tati",

"title": "Tati"

}

}, {

"-KmbsrllgJzV7BA_NeCO": {

"slug": "abel",

"title": "Abel"

}

}]

new Vue({

el: "#app",

data: {

topics

},

methods: {

sortByObjectProperty(prop, getter) {

return (a, b) => {

a = getter(a), b = getter(b)

if (a[prop] < b[prop])

return -1;

if (a[prop] > b[prop])

return 1;

return 0;

}

}

},

computed: {

sortedTopics() {

const getter = v => v[Object.keys(v)[0]]

const sorter = this.sortByObjectProperty("title", getter)

return this.topics.sort(sorter)

}

}

})

{{topic}}

在此代码中(如上面的代码所示), sortByObjectProperty 是一个排序函数生成器 . 您传递任何属性名称,它将为具有该属性的对象生成排序函数 . 为了处理你在 topics 中的数据结构,我添加了一个 getter 参数,这个函数可以用来告诉分拣机如何获得它需要排序的对象 .

我最初担心的是 v[Object.keys(v)[0]] 的表现,但这似乎至少在我自己的满意度中得到了解决 .

如果您不必支持IE,或者您正在使用编译为支持它的javascript,则还可以在不需要按嵌套对象排序的情况下为 getter 参数定义默认值 .

sortByObjectProperty(prop, getter = g => g) {...}

你可以用它作为

const sorter = this.sortByObjectProperty("someProperty")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值