Search code examples
javascriptvue.jsvuejs2vue-componentvue-treeselect

parse json in a vue-treeselect component


In a https://vue-treeselect.js.org/ component, how can I load json? My code is not working

<html>

<head>
    <!-- include Vue 2.x -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@^2"></script>
    <!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
    <script src="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.umd.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">
</head>

<body>
    <div id="app">
        <treeselect v-model="value" :multiple="true" :options="options" />
    </div>
</body>
<script>
    // register the component
    Vue.component('treeselect', VueTreeselect.Treeselect)
    var tree = new Vue({
        el: '#app',
        data: {
            // define the default value
            value: null,
            // define options
            options: function () {
                return JSON.parse(this.json);
            }
        },
    })
    $.getJSON("my.json", function (json) {
        tree.json = json;
    });
</script>

</html>

Solution

  • Put the following code inside the mounted hook :

      let vm = this;
          $.getJSON("https://jsonplaceholder.typicode.com/users", function(json) {
            vm.options = json;
          });
    

    you should update the options property directly in the callback of ajax request.

    <html>
    
    <head>
      <!-- include Vue 2.x -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
      <!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
      <script src="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.umd.min.js"></script>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">
    </head>
    
    <body>
      <div id="app">
        <treeselect v-model="value" :multiple="true" :options="options" />
      </div>
    </body>
    <script>
      // register the component
      Vue.component('treeselect', VueTreeselect.Treeselect)
      var tree = new Vue({
        el: '#app',
        data: {
          // define the default value
          value: null,
          // define options
          options: []
        },
        mounted() {
          let vm = this;
          $.getJSON("https://jsonplaceholder.typicode.com/users", function(json) {
            vm.options = json;
          });
        }
      })
    </script>
    
    </html>