Home > Software design >  Why do I get back zero instead of data in my array?
Why do I get back zero instead of data in my array?

Time:12-02

I'm working on making a in Vue2 calendar for a company but I dont have the data yet so for now I wanted to use my own dummy data. In my calendar view file I have the folowing code:

store.dispatch('resource/add', {
  resource: 'actionEvents',
  data: [
    {
      id: 1,
      startDate: ''
    }
  ]
}, { root: true });

Then in my component Im trying to loop through this and display it as a list:

 <li  v-for= "(validEntry, key) in validEntries"
          :key="validEntry.id" 
          >
            {{key}}
            {{validEntry.startDate}}
 </li>

And in my component my computed properties are as follows:

  computed: {
    validEntries () {
      return this.$store.getters['resource/list']('actionEvents');
    }
  }

What I get back as a key is zero when I'm expecting 1 and no startdate. I'm new to Vue so I dont know how to quite approach my problem. Does someone know what Im doing wrong?

CodePudding user response:

It looks like you're setting the id of your data object to be 1, but in your template, you're using the key variable to display the id. The key variable is a special variable that Vue uses to identify each element in an array when rendering a list. It should not be used to display the id of your data object.

To fix this, you can simply change the line in your template where you display the key to display the id instead:

<li v-for="(validEntry, key) in validEntries"
    :key="validEntry.id" 
    >
      {{validEntry.id}}
      {{validEntry.startDate}}
</li>

This should display the id of each object in your validEntries array, instead of the key variable.

  • Related