Katie Roberts
Katie Roberts

Reputation: 11

load json data in vue

I am trying to load my data/data.json file to my component so that I can display the data when a particular part is clicked.

Snippet of my data

"colors": [
      {"id": 1, "type": "direct", "primary": "red", "hex": [1, 4]},
      {"id": 2, "type": "direct", "primary": "yellow", "hex": [2, 5]},
      {"id": 3, "type": "direct", "primary": "blue", "hex": [3, 6]},
      {"id": 4, "type": "split", "primary": "red", "hex": [1, 7, 8]},
      {"id": 5, "type": "split", "primary": "yellow", "hex": [2, 9, 10]},
      {"id": 6, "type": "split", "primary": "blue", "hex": [3, 11, 12]},
      {"id": 7, "type": "analogous", "primary": "red", "hex": [1, 13, 14]},
      {"id": 8, "type": "analogous", "primary": "yellow", "hex": [2, 15, 16]},
      {"id": 9, "type": "analogous", "primary": "blue", "hex": [3, 17, 18]}
    ]

I have a another data set that is connected to the hex data that's why they are just numbered

For the loading in the data, I have it as follows:

var app = new Vue({
el:"#app",
data:function() {
    return{
        json: null
    }
},
methods: {

}
});

$.getJSON('data/data.json', function (json) {
    app.json = json;
});

What is a good way to add it to my components so that I can properly display what data I am wanting to show?

Upvotes: 1

Views: 5091

Answers (1)

Luis Orduz
Luis Orduz

Reputation: 2887

You could load it within the component itself once it's mounted, using the mounted hook:

// ...
data () {
  return { json: null }
},
mounted () {
  $.getJSON('data/data.json', json => {
    this.json = json
  })
}

Upvotes: 1

Related Questions