How to call specific array values in v-for in Vuejs? - javascript

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')

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);
},
},
sandbox

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);

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

Vue error : "Error in render: "TypeError: right-hand side of 'in' should be an object, got null""

I've create a little API and i tried to get messages, my function return a vector and i want to list the content of this vector for this i use v-for="item in messages" but i have an error: Error in render: "TypeError: right-hand side of 'in' should be an object, got null", i use vuejs cli
my code :
<template>
<div>
<div class="messages">
<ul id="array-rendering">
<li :v-for="item in messages">
{{ item.message.content }}
</li>
</ul>
</div>
</template>
<script>
import {login} from "#/login";
import {Messages} from "#/Messages";
export default {
name: 'Messages',
data() {
return {
messages: null,
}
}
},
mounted() {
login('user', 'pass').then(r=>{
Messages.getMessages(r)
.then(r=>{
this.messages = r
})
})
}
}
</script>
First of all v-for syntax is incorrect. Use "v-for" instead of ":v-for".
The other problem that, you set initial value of messages as null. The problem is you can not loop in null value. You can set empty array or object as initial value.
data() {
return {
messages: [] // or {},
}
}

How to use the props in vue component?

I try to use a prop in a computed value and i keep getting the error:
[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"
found in
---> at src/cmps/space-details/space-imgs.vue
at src/pages/space-details.vue
at src/App.vue
Maybe i'm using the prop wrong?
the component:
<template>
<div v-if="imgUrls.length" class="space-imgs" :class="pics">
<img :src="img" v-for="(img, idx) in imgUrls.slice(0, 5)" :key="idx" />
</div>
</template>
<script>
export default {
props: { imgUrls: Array },
computed: {
pics() {
return `pics-${this.imgUrls.length}`;
},
},
};
</script>
and this is how i pass the prop:
<space-imgs :imgUrls="space.imgUrls" />
Thanks
Pass the prop like below. This will work.
<space-imgs :img-urls="space.imgUrls" />
For avoiding wrong prop data in component. initialize prop with default value.
props: {
imgUrls: {
type: Array,
default: [],
required: true
}
}
Your template will be first rendered before the prop is passed, making imgUrls undefined. So just do this: v-if="imgUrls".

Vue.js - How can I solve [Vue warn]: Error in render: "TypeError: Cannot read property 'port' of undefined"?

My object looks like this :
{
"container_status": {
"name": "/dev-ms",
"port": {
"2233/tcp": [
{
"HostPort": "123"
}
]
}
}
}
I want to display value of key HostPort
I try like this :
console.log(data.container_status.port['2233/tcp'][0].HostPort)
It works
But There exist error :
[Vue warn]: Error in render: "TypeError: Cannot read property 'port' of undefined"
My vue component like this :
<template>
...
<v-flex xs4>
<p class="">{{data.container_status.port['6690/tcp'][0].HostPort}}</p>
</v-flex>
...
</template>
<script>
export default {
...
};
</script>
How can I solve this error?
I think that your data object is not ready in component loading, to solve this try this :
<p class="">{{!!data.container_status?data.container_status.port['6690/tcp'][0].HostPort:""}}</p>
or
<p class="" v-if="data.container_status">{{data.container_status.port['6690/tcp'][0].HostPort}}</p>
I would use a computed for something so complex, and the computed will update the value if data.container_status changes
computed: {
HostPort() {
if(!this.data.container_status) {
return '',
}
return this.data.container_status.port['6690/tcp'][0].HostPort
}
}
<p class="">{{HostPort}}</p>
to make sure that another property is not undefined I would use the get of lodash in the computed https://lodash.com/docs/4.17.15#get

How to set data within VueJS lifecycle hook

I am attempting to use the created lifecycle hook to set a data property on my component. Below is my single-file component. I'm currently seeing "TypeError: Cannot read property 'summary' of undefined" in the console when running this code. This tells me that the template is working with forecastData as the empty object declared in the data property rather than the populated object from created. When I remove the data property entirely I see TypeError: Cannot read property 'currently' of undefined. Clearly, I'm missing something basic here.
<template>
<div>
<p>
<router-link to="/">Back to places</router-link>
</p>
<h2>{{forecastData.currently.summary}}</h2>
<router-link :to="{ name: 'forecast' }">Forecast</router-link>
<router-link :to="{ name: 'alerts' }">Alerts</router-link>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'CurrentWeather',
data () {
return {
forecastData: {}
}
},
created: function () {
this.$http.get('/api/forecast/boston').then((response) => {
this.forecastData = response.data;
}, (err) => {
console.log(err)
});
}
}
</script>
<style scoped>
</style>
You are setting the data asynchronously so it doesn't exist when the object is first mounted. When you try to access forecastData.currently.summary the currently property is undefined, which results in your error.
Use a v-if to avoid the error.
<h2 v-if="forecastData.currently">{{forecastData.currently.summary}}</h2>
Alternatively, define a null summary in your initialization.
data () {
return {
forecastData: {
summary: null
}
}
},

Access to props inside javascript

I just start to learn vuejs 2 but I have an issue, I'm passing a props to a child component like this :
<div class="user">
<h3>{{ user.name }}</h3>
<depenses :user-id="user.id"></depenses>
</div>
And here is how I use it in my child component :
export default {
name: 'depenses',
props: ['userId'],
data () {
return {
depenses: []
}
},
mounted: function () {
this.getDepenses()
},
methods: {
getDepenses: function () {
this.$http.get('myurl' + this.userId).then(response => {
this.depenses = response.body
this.haveDepenses = true
}, response => {
console.log('Error with getDepenses')
})
}
}
}
this.userId is undefined but I'm able to display it with <span>{{ userId }}</span> and I can see in the vuejs console the param userId with the value
Why I have an undefined value in the js ?
Ok I found why I couldn't get my value, thanks to #Saurabh comment, he reminds me that I get my props from an async way, so I had to set a watcher when my props change, like this :
watch: {
userId: function () {
this.getDepenses()
}
},

Categories

Resources