【问题标题】:Vue.js Update value of nested props sync object in componentVue.js 更新组件中嵌套道具同步对象的值
【发布时间】:2017-04-30 12:46:37
【问题描述】:

嗨,我有以下 Vue.js v1.0.28 的问题 - 我有组件

Vue.component('question-editor', {
    template: require('./question-editor.html'),

    props: ['question'],

    methods: {

        addChoice() {
            this.question.choicesArr.push({
                id: null,
                body:'zzz',
                icon:'',
                next:null,
            });

            console.log(this.question.choicesArr);

        },
    }
});

在哪里./question-editor.html

...
    <div class="box-body">
        <div class="form-group" v-for="choice of question.choicesArr">
            <input v-model="choice.body" type="text" class="form-control">
        </div>

    </div>

    <div class="box-footer">
        <button @pointerdown="addChoice" type="submit" class="btn btn-primary">
            Add choice
        </button>
    </div>

我在父组件中使用这个组件是这样的:

<question-editor :question.sync="currentQuestion"></question-editor>

问题是,当我按下“添加选择”按钮并运行方法 addChoice() 时,我在控制台中看到属性 question.choicesArr 有新元素 - 但视图没有改变(我没有看到这个新元素screen - 所以 v-for 不会“看到”这个新元素并且不会刷新自身)。在addChoice() 内做什么来刷新视图以在屏幕上看到question.choicesArr 中的新元素?

【问题讨论】:

    标签: javascript components vue.js


    【解决方案1】:

    我猜 vue 1.x 没有像 2.x 那样检测数组的变化,你可以通过以下操作让 vue 知道数组在 spread operator 的帮助下发生了变化。

    addChoice() {
        this.question.choicesArr= [...this.question.choicesArr, {
            id: null,
            body:'zzz',
            icon:'',
            next:null,
        }];
    }
    

    【讨论】:

    • 我检查了一下 - 由于数组中的新对象中缺少 __ob__:Observer__v-for__1:Fragment,这个解决方案无法正常工作
    【解决方案2】:

    我找到了解决办法:

    addChoice() {
        this.question.choicesArr.push({
            id: null,
            body:'zzz',
            icon:'',
            next:null,
        });
    
        this.question = Object.assign({}, this.question, this.question);
        console.log(this.question.choicesArr);
    
    },
    

    语句this.question = Object.assign({}, this.question, this.question); 将设置__ob__:Observer__v-for__1:Fragment 为推送到数组的新对象。

    我也尝试this.$set(this.question, 'question.choicesArr', this.question.choicesArr);,但这一套只有__ob__:Observer(不是__v-for__1)所以v-for不会更新。

    我在这里读到了它:https://vuejs.org/v2/guide/reactivity.html

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 2018-01-15
      • 2021-11-27
      • 2022-10-12
      • 2020-03-24
      • 2015-06-25
      • 2017-09-22
      • 2018-08-16
      • 2023-04-03
      相关资源
      最近更新 更多