【问题标题】:How do i iterate through JSON in VueJS?如何在 VueJS 中遍历 JSON?
【发布时间】:2019-08-28 07:46:44
【问题描述】:

我在数据库中存储了一些带有键和 JSON 数据的设置,但是当我从 Laravel API 获取这些设置时,它会返回一个数组,这成为将数据重新分配给输入字段的一项繁重的工作。我想知道是否有更简单的方法。

到目前为止,我已经尝试迭代并使用 switch 语句来识别键并重新分配它们。但问题是我无法在循环中访问 VueJS 数据变量。

下面看一下数据库表: Database Table

这是我在 Vue 中使用的对象:

    helpful_notification: {
        email: false,
        sms: false,
        push: false,
    },
    updates_newsletter: {

          email: false,
          sms: false,
          push: false,

    },

这是我迭代结果的代码:

   axios.get('/api/notificationsettings')
      .then(response => {
          var data = response.data;
          let list = [];
          console.log(data)
          $.each(data, function(i, j){
            switch(j.key){
              case 'transactional': 

                  var settings = JSON.parse(j.settings)
                  var x = {
                  transactional : settings
                }
                list.push(x)
              break;
              case 'task_reminder': 
                 var settings = JSON.parse(j.settings)
                  x = {
                  task_reminder : settings
                }
                list.push(x)
                break; 
            }
          });
          this.transactional = list;
          // this.task_reminder= list.task_reminder;
          console.log(list);
      })
      .catch(error => {

      });

【问题讨论】:

    标签: mysql laravel vue.js axios


    【解决方案1】:

    在 JavaScript 中,functions 有自己的 scope,除了少数例外。这意味着,在您的匿名函数中(即:

     $.each(data, function(i, j){
       // this here is the function scope, not the outside scope
     })
    

    ...),this 不是外部作用域,而是函数的作用域

    有两种方法可以在你的函数中使用外部作用域:

    a) 将其放在变量中

     const _this = this;
     $.each(data, function(i, j){
       // this is function scope, 
       // _this is outside scope (i.e: _this.list.task_reminder)
     })
    

    b) 使用arrow function

    $.each(data, (i, j) => {
       // this is the outside scope
       // the arrow function doesn't have a scope. 
    })
    

    上面的简化旨在帮助您访问函数内部的外部范围。但是this 可能会根据使用的上下文而有所不同。您可以阅读有关this here 的更多信息。

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2012-06-07
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2020-01-23
      相关资源
      最近更新 更多