Home > Net >  How to call specific array values in v-for in Vuejs?
How to call specific array values in v-for in Vuejs?

Time:02-10

User.vue

<template>
  <div>
    <!-- <div >{{ user.name }} {{ user.age }}</div> -->

    <div v-for="(item, key) in user" :key="key">
      {{ item }}
    </div>
  </div>
</template>

<script>
import { datalisttwo } from "./datalisttwo";
export default {
  name: "User",
  data() {
    return {
      lists: datalisttwo,
    };
  },
  computed: {
    user: function () {
      return this.lists.find((item) => item.cmd_id === this.$route.params.id);
    },
  },
};
</script>

Working code:- enter image description here

CodePudding user response:

In User.vue you have this comparison:

return this.lists.find((item) => item.id === this.$route.params.id);

but the data you use from datalisttwo.js does not have the property id but instead cmd_id

So that find result will always be undefined which is the error you see in the javascript console:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"

so you'll need to update your find to be the following:

return this.lists.find((item) => item.cmd_id === this.$route.params.id);

CodePudding user response:

I guess you need to return an Array on that computed property. Use filter instead of find.

 computed: {
    user: function () {
      return this.lists.filter((item) => {
        if(item.cmd_id === this.$route.params.id) {
           return item
        }
      })
    }        
 }
  • Related