首页 > 解决方案 > 如何在 VueJS 中遍历 JSON?

问题描述

我在数据库中存储了一些带有键和 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 => {

      });

标签: mysqllaravelvue.jsaxios

解决方案


在 JavaScript 中,函数有自己的作用域,除了少数例外。这意味着,在您的匿名函数内部(即:

 $.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) 使用箭头函数

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

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


推荐阅读