首页 > 解决方案 > 将对象推送到数组数组vue重新渲染失败

问题描述

我有一个奇怪的问题,我似乎无法将对象推送到数组数组。我能够记录组的值....但我无法更新它。

这是我在给定条件下推送到组数组的函数

 calcExclusion: function(){
                this.hideExclusionGroups = true //hides the exclusion groups from app before calculations

                for(var i = 0; i < this.exclusionGroups.length; i++){

                        if(this.numberOfGroups < this.exclusionGroups.length){
                            alert('could not calculate, there are more exclusion groups than groups')
                            return
                        }
                for(var j = 0; j < this.exclusionGroups[i].students.length; j++){

                            if(this.exclusionGroups[i].students.length == 1){
                                alert ('could not calculate, groups must be bigger than 1')
                                return
                            }  

                                //console.log('group number', g,'student to add',this.exclusionGroups[i].students[j])
                            if(j < this.numberOfGroups){
                           this.groups[i].push(this.exclusionGroups[i].students[j].first_name) 
                            console.log(this.groups[i])
                            }                   
                     }

                }

            },

这是我渲染数据的地方

<div v-for="(group, index) in groups" class="d-inline-block bg-white p-2 m-2 border rounded">
                            <span>Group {{ index + 1 }}</span>
                            <ul>
                                <li class="groupItems" v-for="student in group">
                                    {{ student.first_name }}
                                    <input type="hidden" :name="'group['+index+']'" :value="student.id">
                                </li>
                            </ul>
                        </div> 

我可以在某种程度上编辑“组”,但组在这里引用了计算的道具

computed: {
                groups: function () {

                    if(! Number.isInteger(this.numberOfGroups)) {
                        console.log('mal');
                        return [];
                    }

                    const array = [];

                    for (let j = 0; j < this.numberOfGroups; j++) {
                        array[j] = [];
                    }

                    let i = 0;
                    this.students.forEach((student) => {
                        const x = i % this.numberOfGroups;
                        if(student.include === false){
                        array[x].push(student);
                        }
                        i++;
                    });

                    return array;
                },
            },

标签: arraysvue.jsobjectvue-data

解决方案


您正在更新computed属性的结果。结果不是反应性的,这就是为什么您看到您的代码正在更新groups数组,但您在 DOM 中看不到任何更改。

您需要从for 的方法calcExclusion内部移动逻辑。computedgroups


推荐阅读