gpt4 book ai didi

vue.js - 使用 vue.js 在 v-for 中显示随机顺序

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:34 26 4
gpt4 key购买 nike

我正在使用 MongoDB 和 vue.js 来显示我的数据库中的内容,该内容作为一个对象返回,该对象具有多个包含其他对象的属性。

但问题是vue.js的v-for函数是随机显示内容的。在我的数据库中,内容是按字段创建排序的,并停留在这个位置。当我在 this.statics 中获取对象时,如果我对它进行 console.log,我会按字母顺序排列这些字段。但我不明白的是:当我用 v-for 显示它时,它们永远不会以相同的顺序出现。

这是我的 vue 代码:

h3 Static elements
.content-wrap(v-if="Object.keys(statics).length > 0")
.menu-admin
.btn(v-for="(content, key) in statics" @click="activeStatic = key") {{key}}
.content(v-for="(content, key) in statics" v-if="key === activeStatic")
h3 {{key}}
.line
.wrap(v-for="(item, keys) in content")
h4 {{keys}}

问题是 keys 在哪里。

这是返回对象的函数:

getStatics(statics) {
Promise.all(Object.keys(statics).map((key) => {
return PartsService.fetchDataWrap({
id: statics[key]
}).then((res) => {
statics[key] = res.data.values
})
})).then(() => {
this.statics = statics
})
},

console.log for this.statics(永远不会改变):

{__ob__: Observer}
my static bloc: Object
image1: (...)
image2: (...)
text1: (...)
text2: (...)

最佳答案

v-for for object 在遍历对象的键值对时不保证顺序。所以我建议的解决方法是:

使用 computed属性对 Object.keys(statics) 数组进行排序,类似于 sortedStaticsKeys,然后使用排序后的键数组进行迭代。

那么模板应该是这样的:

h3 Static elements
.content-wrap(v-if="sortedStaticsKeys.length > 0")
.menu-admin
.btn(v-for="key in sortedStaticsKeys" @click="activeStatic = key") {{key}}
.content(v-for="key in sortedStaticsKeys" v-if="key === activeStatic")
h3 {{key}}
.line
.wrap(v-for="(item, keys) in content")
h4 {{keys}}

我只是用纯文本更改了您的模板,没有实际运行代码,但它应该以这种方式工作。

关于vue.js - 使用 vue.js 在 v-for 中显示随机顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com