Reputation: 9859
I need to display value for month april. Code:
{{my_dates['2018-04-23']}}
displays:
{
"april":0,
"may":0,
"june":0,
"july":0,
"august":0,
"september":0,
"october":0,
"income_trips":"0.00",
"med_services":"0.00",
"food_services":"0.00",
"accom_services":"0.00",
"collegium":"0.00",
"parking":"0.00",
"wash":"0.00",
"other":"0.00",
"balance":"0.00",
"employees":0,
"season_employees":0,
"complaints":0,
"reviews":0
}
I tried:
{{my_dates['2018-04-23']['april']}}
it's display 0
, but I am getting error:
[Vue warn]: Error in render: "TypeError: Cannot read property 'april' of undefined"
The follow json should be in my my_dates
http://vpaste.net/3A0Th
Code of app:
var app = new Vue({
el: '#app',
data: {
my_dates: {},
},
methods:
{
getTableData: function()
{
// GET /someUrl
this.$http.get('http://127.0.0.1:8000/ponizovka_get_data').then(response => {
// get body data
this.my_dates = response.body;
}, response => {
// error callback
});
}
},
created: function(){
this.getTableData()
}
})
Upvotes: 0
Views: 353
Reputation: 354
{{ my_dates['2018-04-23']['april'] }}
You're right. This is the correct way to access this property, but the error could be related to this value been display before assignment or async operation. You can fix by checking on v-if, using short-circuit, using a computed property (@EmileBergeron suggestion) or even a method.
Fix by checking on v-if
<div v-if="my_dates && my_dates['2018-04-23']">
{{ my_dates['2018-04-23']['april'] }}
</div>
Fix using short-circuit
{{ my_dates && my_dates['2018-04-23'] && my_dates['2018-04-23']['april'] }}
Fix with a computed property (@EmileBergeron suggestion)
<span>{{ april }}</span>
computed: {
april () {
if (!this.my_dates || !this.my_dates['2018-04-23'])
return null;
return this.my_dates['2018-04-23']['april'];
}
}
Fix using a method
{{ getMyDate('2018-04-23', 'april') }}
methods: {
getMyDate (date, month) {
if (!this.my_dates || !this.my_dates[date])
return null;
return this.my_dates[date][month];
}
}
There are other approaches like optional-chaining purpose or idx.
Upvotes: 3
Reputation: 2384
It is because, may be you are getting the data from an async source(fetching from API or something). Unless that data is available vue would try to find my_dates['2018-04-23']
which will be undefined
so you are getting that error.
Wait until you have fetched you data and then display it.
You can use v-if
for that:
<div v-if="my_dates">{{my_dates['2018-04-23']['april']}}</div>
You might still get that error, even after using v-if, so try using computed for getting the values after that.
I hope it helps.
Upvotes: 1