jak
jak

Reputation: 184

How can I load the data from a .json file into a CDN Vue.js app?

I have a .json file with the following structure:

{
       "title": "A"
       "name": "B"
},
{
           "title": "C"
           "name": "D"
},

and I want to use this data inside my Vue.js app. When I copy the data by hand to my my app, everything works:

<script>
  
  new Vue({
    el: '#app',
    data: {
      items: [
    {
           "title": "A"
           "name": "B"
    },
    {
         "title": "C"
         "name": "D"
    },
    ]

How can I load the data directly to my Vue app without having to copy the content of the .json file by hand?

(I'm using the CDN to load Vue.js and hence the usual "import" solutions do not work.)

Upvotes: 1

Views: 2203

Answers (1)

hatef
hatef

Reputation: 6209

You could do something like this:

new Vue({
    el: '#app',
    data: {
        items: null
    },
    created() {
        axios
            .get('./myJson.json')
            .then(response => {
                this.items = response.data;
            })
            .catch((e) => {
                console.error(e)
            })
    }
});

You can import Axios via CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>

And, make sure your JSON is well formatted:

[
  {
    "title": "A",
    "name": "B"
  },
  {
    "title": "C",
    "name": "D"
  }
]

Upvotes: 3

Related Questions