json - 如何使用 Vue $set 更改嵌套 JSON 的值?

标签 json vue.js

[
  {
    "id": 1, 
    "question": "Top Level question", 
    "answers": [
      {"id" : 1, "isSelected" : false}, 
      {"id" : 2, "isSelected" : true}, 
      {"id" : 3, "isSelected" : false}, 
      {"id" : 4, "isSelected" : false}, 
      {"id" : 5, "isSelected" : false}, 
      {"id" : 6, "isSelected" : false}
    ],
    "MaxAllowedChoice" : 1,
    "isEnabled" : true,
    "NowSelected" : 0
  }
]

我写了下一个循环:

for (let question of this.questions) {
  //console.log(question.answers); // array of answers

  for(let answer of question.answers) {
    //this.$set('answer.isSelected', true);
    console.log('Before: ', answer.isSelected);
    // this.$set('answer.isSelected', true); //warning: You are setting a non-existent path "answer.isSelected"
    this.$set('questions.answers.answer.isSelected', true);  // so look like I should to do like this to change value
    // this.$set('questions.answers.answer.isSelected', true); //I can't understand how to write it's correctly... like this or above. 
    console.log('After: ', answer.isSelected);
  }
} 

我需要将所有值更改为 true(或者是否可以更改 true<->false,反之亦然)。我不明白如何达到所需的 key 。 this.$set('answer.isSelected', true); 产生警告,看起来它无法理解应该更改哪个键。

this.$set('questions.answers.answer.isSelected', true); 不会产生警告,但我不确定它是否在正确的位置更改值。 因为我在控制台中看到:

Before: false
After: false
Before: true
After: true

但我的代码中的所有值都应设置为 true。

最佳答案

如果我没理解错的话,你应该不需要使用this.$set()。您应该能够在每次迭代中直接在当前答案上设置属性:

for(let question of this.questions) {
    for(let answer of question.answers) {
        answer.isSelected = true;
    }
}

如果你真的需要使用$set()(这在某些情况下可能有意义),你将不得不在键路径中使用数组索引:

this.$set('questions[0].answers[0].isSelected', true);

关于json - 如何使用 Vue $set 更改嵌套 JSON 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35629173/

相关文章:

javascript - Vue.js 分隔符在引号中不起作用

vue.js - 捆绑后,vuetify 需要 500kb bundle 大小

javascript - vue 选择组件 - 设置默认 Prop ?

javascript - 我如何在 React 中循环遍历 JSON 对象

javascript - 提交用户选择单选按钮值,其中值是从 json 定义的

ruby JSON.pretty_generate(hash,opts) 不使用 opts

javascript - 我可以在 Vue/Vuex 中使用 mapGetters 动态调用 getter 吗?

ajax - 处理 Ajax 请求和响应 Zend 框架

javascript - js 数组转为 json 但有些值消失了

javascript - 提交前验证问题