Asked By: Anonymous
The data is on firebase, and I want to show only 1 object with [objectNumber] see {{ligler[1].name}}
in the template, but when I do this it works but I get errors:
- Error when rendering component
- Uncaught TypeError: Cannot read property ‘name’ of undefined
I think, the problem is that the data loaded before the component.
When I use v-for, it show the name off all objects without errors, but I only want to show one object.
The template looks like:
<template>
<div id="app">
<h1>{{ligler[1].name}}</h1>
</div>
</template>
the script:
<script>
import Firebase from 'firebase'
let config = {
apiKey: "xxxxxxxxxx",
authDomain: "xxxxxxxxxx",
databaseURL: "https://xxxxxxxxxx.firebaseio.com"
}
let app = Firebase.initializeApp(config);
let db = app.database();
let ligRef = db.ref('ligler');
export default {
name: 'app',
firebase: {
ligler: ligRef
}
}
</script>
I tried to add v-if to the h1, but that doesn’t work.
How can I fix this errors?
Solution
Answered By: Anonymous
Put a null check like this:
<h1>{{ligler[1] && ligler[1].name}}</h1>
Using &&
or ||
are called logical operator short circuiting meaning they don’t evaluate the right hand side if it isn’t necessary. This is widely used due to it’s brevity.
Here if ligler[1]
is undefined, it will not evaluate ligler[1].name
and you will not be getting the error, which is equivalent of putting a if before accessing the inside properties.
It makes more sense to use v-if
if you have more component where you access other properties of ligler[1]
as well, otherwise above code is better.
<div v-if="ligler[1]">
<h1>{{ligler[1].name}}</h1>
<h1>{{ligler[1].age}}</h1>
<h1>{{ligler[1].etc}}</h1>
</div>