0

I am doing my first steps in Vuejs. I have an object member, order by names of the members. But when I do a v-for, it is ordered by the object index.

How can I disable that behaviour or do again my order by member.name?

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    members: {
        '3432':{'name':'Andreas', "age":39},
        '234':{'name':'Frank', "age":21},
        '333':{'name':'Dieter', "age":2},
        '8644':{'name':'Klaus', "age":66}
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <h1>{{ message }}</h1>
    <ul v-for="(member) in members" v-bind:key="member.name">
        <li> {{ member.name }} {{ member.age }}</li>
    </ul>
</div>
str
  • 42,689
  • 17
  • 109
  • 127
Andi S.
  • 317
  • 1
  • 11
  • Does this answer your question? [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – str Oct 14 '20 at 08:28
  • 1
    Integer indices are always ordered. That is a language feature and not related to Vue.js. Use an array if the order is important. – str Oct 14 '20 at 08:28
  • There's a note/warning about this on the [docs](https://vuejs.org/v2/guide/list.html#v-for-with-an-Object) (scroll down a bit and you should see it) – Hiws Oct 14 '20 at 08:39
  • I saw this note, but was thinking that maybe v-bind:key would help to change this behavior. I think i really should use array instead of object. – Andi S. Oct 14 '20 at 08:42

1 Answers1

0

Its a bad idea to loop an object. Use an array instead

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    members: [
        {'name':'Andreas', "age":39},
        {'name':'Frank', "age":21},
        {'name':'Dieter', "age":2},
        {'name':'Klaus', "age":66}]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <h1>{{ message }}</h1>
    <ul v-for="member in members" v-bind:key="member.name">
        <li> {{ member.name }} {{ member.age }}</li>
    </ul>
</div>
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • v-bind:key is not really required here, or is it? I think you are right, I should use array instead of objects – Andi S. Oct 14 '20 at 08:49
  • @AndiS. its not neccessary in this case. its required if you loop components. however, try always to bind an key so you arent on the wrong side – bill.gates Oct 14 '20 at 08:50