I am building an app using vue js. In the app I am getting all the data from JSON file and and when I try to load JSON file using jQuery's getJSON() method then it throws an error during rendering the web page
Error when rendering root instance: vue.js:2229 Uncaught TypeError: Cannot read property 'title' of null
My understanding is that I am loading json file in "created method" using jQuery's getJSON() method which is an asynchronous method, so vue js tries to populate json data in my template as soon as it creates the vue instance without waiting for the 100% loading of the json file, so it throws the error "Cannot read property 'title' of null" as I have set the initial value of data model to null. Am I correct? If yes then how can I avoid it ? One way is to use "synchronous ajax request" which is working fine in my case but I think its not a good idea to still use a synchronous request in 2017! as it will frustrate the users in case of long loading duration for JSON file. Guys please help me
Example using jQuery's getJSON() method:
var viewModel = new Vue({
el: '#templateBody',
data: {
jsonData: null
},
created: function() {
var self = this;
self.fetchJSONData();
},
methods: {
fetchJSONData: function() {
var self = this;
$.getJSON("data.json", function(data, status, xhr) {
if (status == "success") {
self.jsonData = data;
} else {
console.log("JSON data not Loaded.");
}
});
}
}
});
JSON: {
"title": "Tilte Text",
"bodyText": "Body text",
"_classes": {
"titleClass": "className"
}
}
<div id="templateBody">
<h1 id="title" v-if="jsonData.title" :class="jsonData._classes.titleClass">{{ jsonData.title }}</h1>
</div>
The problem in the code is the null initial value of jsonData in data model. If we replace the null value of jsonData(jsonData: null) with an empty object(jsonData: {}) then we do not get the error
Uncaught TypeError: Cannot read property 'title' of null
My understanding is that when we write v-if="jsonData.title" then vue considers jsonData as a javascript object and tries to find the value of title but we have assigned the null value to it that's why it returns the TypeError. It is not an issue of aysnc loading of JSON file.
var viewModel = new Vue({
el: '#templateBody',
data: {
jsonData: {}
},
created: function() {
var self = this;
self.fetchJSONData();
},
methods: {
fetchJSONData: function() {
var self = this;
$.getJSON("data.json", function(data, status, xhr) {
if (status == "success") {
self.jsonData = data;
} else {
console.log("JSON data not Loaded.");
}
});
}
}
});
JSON: {
"title": "Tilte Text",
"bodyText": "Body text",
"_classes": {
"titleClass": "className"
}
}
<div id="templateBody">
<h1 id="title" v-if="jsonData.title" :class="jsonData._classes.titleClass">{{ jsonData.title }}</h1>
</div>