Vue.js Dynamic JSON import based on select

3.5k Views Asked by At

I am trying to display a large set of json datasets, 7000+ of them. I have a select on my page which allows a user to choose which dataset they want to view. A small example might be colors, only imagine I have 7000 of them. Here's a simple mockup.

Select a color [Dropdown]

Name: Red
RGB: 255 0 0
Hex: #FF0000
Complementary Colors: #00FFFF, #FFB03B, #B64926, #8E2800
Analogous Colors: $FF004C, #FF001A, #FF1A00, #FF4D00
Triads: #00FF00, #0000FF, #FF1A00, #FF4D00
etc.

I thought I could dynamically load the appropriate json file for display when the value of the select changed, but I learned that use of

this.$http.get

does not work for local files. I know I can import the file at the top of my export default statement, but I can't import 7000 files at that point in my code. Also, importing a file inside a computed value or a method is not allowed.

What is the best approach for handling large numbers json data files that I need to load dynamically? Am I forced to go to a valid API way of doing this? Or can I just simply load the files locally as requested by the dropdown selector?

1

There are 1 best solutions below

0
On

I discovered that I can load these files from the static folder. The relevant parts of the template and script sections look like this.

<template>
...
<select v-model="selected" @change="getData">
  <option v-for="key in data" v-bind:value="key.name">
    {{ key.name }}
  </option>
</select>
...
</template>

<script>
...
computed: {
  getData: function (selected) {
    var link = '/static/data/' + this.selected + '.json'
    this.$http.get(link).then((response) => {
      console.log(response.body)
      this.langData = response.body
    }, function (error) {
      console.log(error.statusText)
    })
  }
...
</script>