简体   繁体   English

如何使用 vuejs 组件获取 json 数据?

[英]How to fetch json data using vuejs component?

I want to access json data from external file using vue component but I am not able to get any output in web page.The below is my code which I have tried.Can anyone help me out?我想使用 vue 组件从外部文件访问 json 数据,但我无法在网页中获得任何输出。下面是我尝试过的代码。有人可以帮我吗?

The below is Json data that included the models which I want to display on web page下面是包含我想在网页上显示的模型的 Json 数据

{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }

 Vue.component('single-model', { data: function() { return { myData: [] } }, template: `<div v-for="model in myData"> <p>{{model.title}}</p> <hr> </div>`, created: function() { this.fetchData(); }, methods: { fetchData: function() { var url = 'j.json'; axios.get(url) .then(function(res) { this.myData = res.data.models; }); } } }); var vm = new Vue({ el: '#app', });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> <div id="app"> <single-model></single-model> </div>

  1. As you might have noticed white running the provided snippet, template can have only one child element, using a v-for on the outermost element will create multiple children.正如您可能已经注意到 white 运行提供的代码段, template只能有一个子元素,在最外层元素上使用v-for将创建多个子元素。

  2. this in your case is not referring to the vue-component in fetchData function. this在你的情况是不是指在VUE组分fetchData功能。

 methods:{ fetchData() { var url = ''; axios.get(url) .then((res) => { this.myData = res.data; }); } },
Try replacing with the above snippet in your code. 尝试在您的代码中替换为上述代码段。

this on your code is not referring to your Vue Component.您代码中的this不是指您的 Vue 组件。

I think, the easiest way to solve this issue is by creating a new variable to refer to your Vue Component我认为,解决此问题的最简单方法是创建一个新变量来引用您的 Vue 组件

fetchData: function() {
      var url = 'j.json';
      var self = this;

      axios.get(url)
        .then(function(res) {
          self.myData = res.data.models;

        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM