Reputation: 820
User.vue
<template>
<div>
<!-- <div class="cont-color">{{ 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:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue
How to call specific value from an array in Vuejs.
At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.
If i remove the v-for and write directly like this {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as
[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')" TypeError: Cannot read properties of undefined (reading 'name')
Upvotes: 1
Views: 1047
Reputation: 303
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
}
})
}
}
Upvotes: 1
Reputation: 2823
I think problem is in your computed block, use below solution
computed: {
user: function () {
return this.lists.find((item) => item.cmd_id === this.$route.params.id);
},
},
Upvotes: 1
Reputation: 5060
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);
Upvotes: 1