Error in nextTick: “TypeError: Cannot read properties of undefined (reading ‘toggleRowSelection’)”

在使用elementUI里的带Checkbox表格时,想默认选中第一行,采组件库里的方法:

mounted() {
	this.defaultChecked([this.nodesData[0]]);
},
methods: {
        // 第一行默认选中
        defaultChecked(rows) {
            this.$nextTick(() => {
                console.log(this.$refs.multipleTable);
                this.nodesData.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row, true);
                    }
                });
            });
        }
    }

或者直接在mounted()里面写:

this.$refs.multipleTable.toggleRowSelection(this.nodesData[0], true);

都不能实现想要的效果,用了setTimeout延时调用还是不行,一直报toggleRowSelection未定义。
在这里插入图片描述
所以只能去找解决方法:

// 第一行默认选中
        defaultChecked() {
            var that = this;
            that.$nextTick(() => {
                console.log(this.$refs.multipleTable);
                that.nodesData.forEach(row => {
                    for (const j in that.multipleSelection) {
                        if (row.id === that.multipleSelection[j].id) {
                            console.log('same');
                            that.$refs.multipleTable.toggleRowSelection(row, true);
                        }
                    }
                });
            });
        },

        // 在调用的时候延时三秒
        // 在调用接口获取表格内容后调用
        setTimeout(() => {
            this.defaultChecked();
        }, 3000);// 测试过了,比三秒短的话,还是会报错

找到的解释是:刚开始逻辑虽然能够正常执行,但是由于DOM并没有更新完,所以打印this.$refs为空。
暂时先记一下,之后再补充。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐