Search code examples
vuejs2v-for

VUEJS V-FOR acting weird


I need a simple v-for to render object properties in a list.

<div
   v-if="profileData && profileData.length > 0"
>
  <ul
    v-for="value in profileData"
    :key="value.id"
  >
    <li>{{value.id}}</li>
  </ul>
</div>

In the script:

profileData: {},
created() { 
  const userId = this.$route.params.userId
  const currentUser = this.$store.getters.currentUser
  const profileData = this.$store.getters.profileData 
  console.log('profileData in seeProfile: ', profileData) }

(profileData comes from an api response)

I did exactly the same in two other pages (just rendering different objects) and it worked. With this code, in the console I get value is undefined. If I remove :key="value.id" (it becomes red in the editor but it still works), and instead of the list items I type only {{ value }}}, then the object properties get rendered ( but in the ugly format of a js object). How can it be? What am I doing wrong? Thank you


Solution

  • The api has been changed, so the working code is slightly different from the original one. Here's the template:

    <div
      v-if="listData.length"
    >
      <ul>
        <li>Name: <b>{{ profileData.user.first_name }}</b></li>
        <li>Surname: <b>{{ profileData.user.last_name }}</b></li>
        <li>Username: <b>{{ profileData.user.username }}</b></li>
        <li>Car: <b>{{ profileData.if_cars_owned }}</b></li>
        <li v-if="profileData.if_cars_owned === true">
          Car model: {{ profileData.user_car_type }}
        </li> 
        <li v-if="profileData.if_cars_owned === true">
          Car power: {{ profileData.user_car_powered_by }}
        </li> 
        <li>Motorcycle: <b>{{ profileData.if_motorcycle_owned }}</b></li>
        <li v-if="profileData.if_motorcycle_owned === true">
          Motorcycle model: {{ profileData.user_motorcycle_characteristic }}
        </li>
      </ul>
    </div>
    

    Script:

    created(){
        const profileData = this.$store.getters.profileData
        this.profileData = profileData
        console.log('profile data in profilo: ', profileData)
      },
    

    I've also updated

    <div
      v-if="listData.length"
    >
    

    and in the script

    computed: {
        ...,
        listData() {
          let list = Object.values(this.profileData);
          return list;
        }
    },
    

    following the advice of @Adrián S. Basave. Thanks to anyone who tried to help. x