VueJS - 将本地json文件中的数据读入vis.js时间轴

Cod*_*rPJ 5 html javascript jquery vis.js vuejs2

我的问题是从本地JSON文件中读取.我正在创建一个VueJS应用程序.我试图将数据从json文件加载到这样的Vue组件中,

<script> 
 
  var container = {};
  
  var items = {};
  var options = {};
  var timeline = {};

  export default {
    
    mounted() {
      
      // DOM element where the Timeline will be attached
      container = document.getElementById('mynetwork');

      // Configuration for the Timeline
      options = {
        width: '100%',
        height: '200px',
        showTooltips: true
      };

      // initialize your network!
      timeline = new vis.Timeline(container, items, options);

      timeline.on('select', function(properties){
        
        console.log(properties);

        var itemNo = properties.items[0];

        switch(itemNo){
          case 1:
            window.open('./../../../generalcheckup1.html');
            break;
          case 2:
            window.open('./../../../scan1.html');
            break;
          case 3:
            window.open('./../../../surgery1.html');
            break;
          case 4:
            window.open('./../../../generalcheckup2.html');
            break;
          case 5:
            window.open('./../../../scan2.html');
            break;
          case 6:
            window.open('./../../../generalcheckup3.html');
            break;
          default:
            console.log('Item out of focus');
        }

      });
      
    },

    data(){
      return{
        
      }
    },

    created: function(){
        $.getJSON('http://localhost:8080/#/timeline.json',function(json){
          console.log('Entered inside');
          this.items = new vis.DataSet([json]);
          console.log(json);
        });
    },

    methods:{
     
    }
  }

</script>
Run Code Online (Sandbox Code Playgroud)

我有一个小的JSON文件,timeline.json,存在于我的文件夹中,如下所示,

{
  "id": 1,
  "content": "General Checkup",
  "start": "2017-01-20",
  "title": "General check-up"
}
Run Code Online (Sandbox Code Playgroud)

当我尝试加载脚本时,控件似乎没有进入该$.getJSON函数.控制台上没有错误.我做错了什么?

小智 26

您只需使用import读取静态JSON文件即可.然后分配数据.

import Timeline from '../data/timeline.json';
export default{
    data(){
        return {
            Timeline
            }
    },
Run Code Online (Sandbox Code Playgroud)


Rob*_*Rob 6

如果有很多 json 文件,您还可以动态加载它们。在 vue 中使用 import 语句加载太多会使浏览器陷入困境,或者如果你有太多 json,浏览器就会崩溃。因此,您也可以单独动态加载 json 文件。

只需创建一个方法并设置一个等于 json 资源的变量即可。当用户需要资源时触发该方法。

methods: {
  getJsonFile (index) {
  this.currentJsonFile = require('./assets/' + index + '.json')
}
Run Code Online (Sandbox Code Playgroud)

JSON 将被自动解析。


Pra*_*epb 4

我认为问题出在您的 Json 文件的 URL 上。尝试将 Json 文件放入该static文件夹中。如果不存在则创建一个。它应该与文件夹级别相同src。然后将 Json 文件放置在该文件夹中。完成上述建议后,使用如下所示的 URL:

$.getJSON('static/timeline.json', function .......
Run Code Online (Sandbox Code Playgroud)