【问题标题】:Random order display in v-for with vue.js使用 vue.js 在 v-for 中显示随机顺序
【发布时间】:2025-12-01 05:40:01
【问题描述】:

我正在使用 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
  })
},

this.statics 的控制台.log(从不更改):

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

【问题讨论】:

  • 您好,您的问题解决了吗?我有同样的问题并试图解决这个问题,但仍然没有实现。

标签: vue.js v-for


【解决方案1】:

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}}

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

【讨论】: