像这样的东西 . 在这里,我显然没有使用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")