【问题标题】:How to change value of nested JSON with Vue $set?如何使用 Vue $set 更改嵌套 JSON 的值?
【发布时间】:2016-06-08 08:06:30
【问题描述】:
[
  {
    "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(或者是否可以更改 truefalse,反之亦然)。我无法理解如何获得所需的密钥。 this.$set('answer.isSelected', true); 产生警告,看起来它无法理解它应该更改什么键。

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

之前:假
之后:假
之前:是的
之后:真

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

【问题讨论】:

    标签: json vue.js


    【解决方案1】:

    如果我理解正确,您不需要使用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);
    

    【讨论】:

      猜你喜欢
      • 2018-07-31
      • 2021-10-20
      • 2011-04-19
      • 2021-02-11
      • 1970-01-01
      • 2019-01-24
      • 2019-04-16
      • 1970-01-01
      • 2021-03-01
      相关资源
      最近更新 更多