Reputation: 81
I want to access json data from external file using vue component but I am not able to get any output in web page.The below is my code which I have tried.Can anyone help me out?
The below is Json data that included the models which I want to display on web page
{
"models": [
{
"title": "IRIS",
"project": "ABC",
"category": "SINGLES",
"bedrooms": 3
},
{
"title": "LILAC",
"project": "ABC",
"category": "DOUBLE",
"bedrooms": 4
},
{
"title": "ASTER",
"project": "ABC",
"category": "SINGLES",
"bedrooms": 4
}
]
}
Vue.component('single-model', {
data: function() {
return {
myData: []
}
},
template: `<div v-for="model in myData">
<p>{{model.title}}</p>
<hr>
</div>`,
created: function() {
this.fetchData();
},
methods: {
fetchData: function() {
var url = 'j.json';
axios.get(url)
.then(function(res) {
this.myData = res.data.models;
});
}
}
});
var vm = new Vue({
el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app">
<single-model></single-model>
</div>
Upvotes: 0
Views: 519
Reputation: 255
this
on your code is not referring to your Vue Component.
I think, the easiest way to solve this issue is by creating a new variable to refer to your Vue Component
fetchData: function() {
var url = 'j.json';
var self = this;
axios.get(url)
.then(function(res) {
self.myData = res.data.models;
});
}
Upvotes: 0
Reputation: 625
As you might have noticed white running the provided snippet, template
can have only one child element, using a v-for
on the outermost element will create multiple children.
this
in your case is not referring to the vue-component in fetchData
function.
methods:{
fetchData() {
var url = '';
axios.get(url)
.then((res) => {
this.myData = res.data;
});
}
},
Upvotes: 1