0

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>

mplungjan
180k29 gold badges183 silver badges246 bronze badges
asked Feb 17, 2020 at 14:17
2
  • @mplungjan axios is working fine without component and I am using local file called j.json. Commented Feb 17, 2020 at 14:26
  • Try use arrow function axios.get(url).then((res) => {this.myData = res.data.models;}); I suppose in vm is not what you expect. Commented Feb 17, 2020 at 14:28

2 Answers 2

1
  1. 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.

  2. 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;
		});
 }
 },
Try replacing with the above snippet in your code.

answered Feb 17, 2020 at 15:41

Comments

0

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;
 });
 }
answered Feb 17, 2020 at 18:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.