Skip to content
Advertisement

How do I fetch JSON data with Vue and Axios

I’m trying to fetch product data from a JSON file, but can’t get it to work. I’ve tried several things and searched the internet for a solution but none of the examples on the internet equals my situation. I’m new to both vue and axios, so please excuse my ignorance.

This is what I have so far:

JavaScript

The json file is as follows

JavaScript

The problem is only with the fetching of the data from a JSON file, because the following worked:

JavaScript

Advertisement

Answer

As the warnings suggest, please do the following:

  1. Rename the data array from results to products since you are referencing it by the latter one as a name during render.
  2. Make your data option a function returning an object since data option must be a function, so that each instance can maintain an independent copy of the returned data object. Have a look at the docs on this.
JavaScript
JavaScript

Also, since you’re not using CDN (I think), I would suggest making the template a component with a separate Vue file rather than doing it inside template literals, something like that:

Products.vue

JavaScript

And then in your main JS file or anywhere else requiring this component:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement