Home > database >  Vuejs v-for not working with my data, is my data not formatted correctly?
Vuejs v-for not working with my data, is my data not formatted correctly?

Time:07-02

Code screenshot of a v-for not working with my data

Not sure why the data is showing up as undefined. Is the data not formatted correctly? I've tried several ways to adjust it and nest it differently but nothing is working out so far.

<template>
  <main>
    <AboutMeComponent v-for="i in about" :key="i.posts.id" :title="i.posts.title" :body="i.posts.body" :skills="i.posts.skills"
      :img="i.images.img" />
  </main>
</template>

<script>
import AboutMeComponent from '../components/AboutMeComponent.vue';
export default {
  data() {
    return {
      about: {
        posts: [
          { id: 1, title: "About Me", body: `Body 1` },
          { id: 2, title: "Skills"  },
          { id: 3, title: "Hobbies", body: "Body 3" },
        ],
        images: [
           { img: 'figma.png'},
           { img: 'figma.png'},
           { img: 'figma.png'},
        ]
      }
    }
  },
  components: {
    AboutMeComponent
  }
}
</script>

CodePudding user response:

I think you are need to set the v-for loop on the about.posts, not on the about. Also, if the img is used for the post, I would suggest you keep them with the post, instead of separated.

So your data will be:

 data() {
    return {
      about: {
        posts: [
          { id: 1, title: 'About Me', body: 'Body 1', img: 'figma.png' },
          { id: 2, title: 'Skills', body: 'Body 2', img: 'figma.png'  },
          { id: 3, title: 'Hobbies', body: 'Body 3', img: 'figma.png' },
        ],
      }
    }
  },

And now you can loop over about.posts:

<AboutMeComponent v-for="post in about.posts" :key="post.id" :title="post.title" :body="post.body" :img="post.img" />

I left skills out, as they are not in your data.

Just a small suggestion: using variable names as i makes your code harder to understand. If you had used about in about, you would have felt that this was not what you wanted, because you wanted something to do with a post in posts.

Hope this helps.

CodePudding user response:

Maybe you should band the index

'

<AboutMeComponent v-for="(i,index) in about" :key="i.posts.id" :index=index :title="i.posts.title" :body="i.posts.body" :skills="i.posts.skills"
  :img="i.images.img" />

'

and I think you should show us the error page, such as the console.log in f12,, so that we can solve the problem better

And from your fake data it seems that there is no skills field in posts

  • Related