【问题标题】:Javascript / vue.js receive jsonJavascript/vue.js 接收json
【发布时间】:2016-06-16 16:34:41
【问题描述】:

我正在尝试在我的 vue.js 应用中接收 json,如下所示:

  new Vue({
            el: 'body',
            data:{
                role: '',
                company: '',
                list:[],
                created: function() {
                  this.getJson();
                },
                methods: {
                    getJson: function(){
                        $.getJSON('http://domain.dev/data',function(task){
                          this.list = task;
                        }.bind(this));
                    }
                }
            }
        });

但结果为空?当我在邮递员中测试这个时,url 返回 json。我在这里做错了什么?

编辑:

JSON(测试数据):

{"EmployeeId":1,"RoleId":5,"DepartmentId":6,"InternId":1,"FirstName":"Zoe","LastName":"Altenwerth","Bio":"Quidem perferendis.","email":"Kole.Bechtelar@hotmail.com","LinkedIn":"Sterling.Schowalter@example.net","Gender":0,"password":"$2y$10$bbUlDh2060RBRVHSPHoQSu05ykfkw2hGQa8ZO8nmZLFFa3Emy18gK","PlainPassword":"gr^S=Z","remember_token":"D528C0Ba1Xzq3yRV7FdNvDd8SYbrM0gAJdFUcOBq4sNEJdHEOb2xIQ0geVhZ","Address":"0593 Dallin Parkway Apt. 499\nBotsfordborough, MT 12501","Zip":"21503-","City":"East Janiston","ProfilePicture":null,"BirthDate":"2002-10-13 00:00:00","StartDate":"1995-11-09 21:42:22","EndDate":"2011-01-27","Suspended":0,"created_at":"2016-02-29 12:21:42","updated_at":"2016-03-02 11:53:58","deleted_at":null,"role":{"RoleId":5,"RoleName":"Superadministrator","Description":"Mag administrators toevoegen en bewerken","deleted_at":null,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"},"department":{"DepartmentId":6,"CompanyId":12,"DepartmentName":"com","Description":"Accusantium quae.","deleted_at":null,"created_at":"2016-02-29 12:21:41","updated_at":"2016-02-29 12:21:41","company":{"CompanyId":12,"CompanyName":"Dare, Bailey and Bednar","Logo":null,"Address":"85762 Tabitha Lights\nWest Jettie, AK 20878-2569","Zip":"29601","City":"Traceside","KvKNumber":"84c70661-9","EcaboNumber":"fdee61e3-a22d-3332-a","deleted_at":null,"created_at":"2016-02-29 12:21:41","updated_at":"2016-02-29 12:21:41"}}}

【问题讨论】:

    标签: javascript json vue.js


    【解决方案1】:

    Vue3 更新

    const app = Vue.createApp({
        data: function() {
            return {
                role: '',
                company: '',
                list:[]
            };
        },
        beforeMount: function() {
            this.getJson();
        },
        methods: {
            getJson: function(){
                $.getJSON('http://domain.dev/data',function(task){
                    this.list = task;
                }.bind(this));
            }
        }
    });
    
    const mountedApp = app.mount('body');
    

    【讨论】:

      【解决方案2】:

      以@vbarbarosh 的回答为基础,但使用浏览器的 fetch api

      a.json:

      {"hello": "welcome"}
      

      index.html:

      <div id="app">
          <pre>{{ json.hello }}</pre>
      </div>
      
      <script type="text/javascript">
      new Vue({
          el: '#app',
          data: {
              json: null
          },
          created: function () {
            fetch("/a.json")
              .then(r => r.json())
              .then(json => {
                this.json=json;
              });
          }
      });
      </script>
      

      【讨论】:

      • 你选择created而不是beforeCreate有什么特别的原因吗? (Vue lifecycle diagram 显示所有可用的钩子。)
      【解决方案3】:

      这是一个如何将外部 JSON 数据加载到组件中的小示例:

      a.json:

      {"hello": "welcome"}
      

      index.html:

      <div id="app">
          <pre>{{ json.hello }}</pre>
      </div>
      
      <script type="text/javascript">
      var app = new Vue({
          el: '#app',
          data: {
              json: null
          }
      });
      $.getJSON('http://localhost/a.json', function (json) {
          app.json = json;
      });
      </script>
      

      ---已编辑---

      或者created事件:

      <script type="text/javascript">
      new Vue({
          el: '#app',
          data: {
              json: null
          },
          created: function () {
              var _this = this;
              $.getJSON('http://localhost/a.json', function (json) {
                  _this.json = json;
              });
          }
      });
      </script>
      

      【讨论】:

      • _this 是什么意思?为什么我们不能使用this
      • @SuatAtanPhD 有 3 种方式可以访问this。 1)使用像_this这样的变量; 2) 使用箭头函数() =&gt; {...}; 3) 使用绑定function(){}.bind(this)。我选择第一个选项。
      • @vbarbarosh _this 如何连接到数据?,在普通的 vue 应用程序中 this.json = json 有效,但在这种情况下无效。 (你的方法确实有效,只是好奇如何)
      • 上面两行 - var _this = this;.
      • 我是 vue 的新手 - 出于我的目的,我将其视为 jquery 的替代品。不知何故在 vue 中使用 .getJSON 感觉不对.. 为什么不用 axios? vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
      【解决方案4】:

      您也必须将this 绑定到外部函数。

      getJson: function () { ...}.bind(this)
      

      【讨论】:

      • 任务是否包含任何数据?
      • 当我 console.log(task);它没有在控制台中显示任何内容?! (我包括 jquery)
      • 这不是问题,因为它返回 json 请看我的编辑。
      • 那么您的 Ajax 请求似乎以某种方式失败了。无论如何,关于您最初的问题,您可以检查this.list = 'test' 是否可以解决您的问题。
      • 哦,我发现这是一个初学者的错误 -_- 我在数据部分中创建了()。感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 2015-02-08
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 2012-03-06
      • 2012-03-06
      相关资源
      最近更新 更多