mysql - 如何在 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 => {
});
解决方案
在 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
此处阅读更多信息。
推荐阅读
- lerna - 使用共享库时 Yarn 工作区的最佳实践
- c++ - RISC-V 内联汇编结构优化了
- java - 错误:语句关闭后不允许任何操作
- react-native - flexDirection 对 React Native 中的 Text 元素没有影响?
- node.js - 如何处理未处理的拒绝ReferenceError:使用Node Sequelize时未定义err?
- php - 通过自定义 css 在 woocommerce 中的产品页面上居中图像
- doctrine-orm - Symfony - 在迁移中禁止交流,Doctrine
- c# - 如何根据c#中的条件关闭验证
- linux - 提取后删除提取文件,拆分文件
- javascript - ScrollMagic 取消伪选择器