3

I'm using MongoDB and vue.js to display a content from my db, the content is returned as an object with several properties containing other objects.

But the problem is that the v-for function of vue.js is randomly displaying the content. In my DB, the content is sorted by field creation, and stay in this position. When I get the object in this.statics, if I console.log it, I have those fields by alphabetic sort. But what I don't understand is : when i display it with a v-for they never come out in the same order.

here is my vue code :

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

the problem is where keysis.

here is my function who returns my object:

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 (who never change) :

{__ob__: Observer}
  my static bloc: Object
    image1: (...)
    image2: (...)
    text1: (...)
    text2: (...)
1
  • Hi, did you solve your problem ? I've got same issue and trying to solve this but still not achieved. Commented Jan 12, 2018 at 6:20

1 Answer 1

0

v-for for object doesn't guarantee orders when iterating over object's key value pairs. So my suggested ways to solve it is:

Use a computed property to sort the Object.keys(statics) array, something like sortedStaticsKeys, and then iterate using the sorted key array.

Then the template would be something like:

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

I just changed your template in plain text with no actual code running, however it should work this way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.