复选框上选中的道具没有相应更新

时间:2019-03-09 19:22:31

标签: javascript vue.js

我有一个组件会根据响应的数量循环遍历。我正在将响应作为对此组件的支持。

在组件中,我有一个复选框,仅当满足条件时,才需要将其设置为选中状态。例如,如果检查了响应的single answer,则在任何给定时间都只能检查循环中的一项。

当我选中该复选框时,我向根发出一个事件(因为我位于可拖动组件中),然后我在父级中侦听该组件并在update函数中运行一条语句。

但是,尽管我传递了响应,然后将其绑定到复选框的checked值,但这在组件内没有生效。

ResponseComponent

<template>
    <div class="row">
        <input :checked="response.correct" @change="responseCorrectStatusChanged" type="checkbox" />
    </div>
</template>

<script>
export default {
    props: {
        response: {
            required: true
        }
    },

    methods: {
        responseCorrectStatusChanged(e) {
            this.response.correct = e.target.checked;

            this.$root.$emit('response:updated', this.response);
        }
    }
}
</script>

ParentComponent

<template>
<draggable v-model="response">
    <response v-for="response in responses" :key="response.id"></response>
</draggable>
</template>

<script>
export default {
    data() {
        return {
            responses: []
        }
    },

    mounted() {
        this.$root.$on('response:updated', this.responseUpdated);
    },

    methods: {
        responseUpdated(eventResponse) {
            const index = this.responses.findIndex(response => {
               return response.id === eventResponse.id;
            });

            if (!this.canSelectMultiple()) {
                const selected = this.responses.filter(response => {
                    return response.correct;
                });

                if (selected.length > 1 && eventResponse.correct) {
                    selected.forEach(response => {
                        response.correct = false;
                    });
                }
            }

            this.responses[index] = eventResponse;
        },

        canSelectMultiple() {
            return this.questionTypeId === '1';
        }
    }
}
</script>

我觉得我做这件事的方式要么是错误的,要么是我犯了一个愚蠢的错误。我也确实注意到,当我在forEach方法中执行responseUpdated循环时,此后即使eventResponse.correct为true,循环也为false,即使事实并非如此。无论如何都会受到影响。

0 个答案:

没有答案
相关问题