1. 问题描述
最近写前后端分离项目中 遇到需获取到后端返回对象的集合属性值的大小的场景
一开始使用如下的解决方法,直接使用集合的 size 属性:
<el-table-column label="操作" width="100" align="center" fixed="right">
<template slot-scope="scope">
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除"
:disabled="scope.row.childList.size != 0"/>
</template>
</el-table-column>
但是运行时候发现页面无法正常显示 页面调试后报错如下:
2. 问题分析
显然前端无法解析当前 size 属性值,出现这个问题的原因是在我们使用集合时没有事先进行非空判断,出现 null.size 的错误。
为了保险起见还是再使用 size 属性前先使用 childList != undefined 判断非空。
3. 解决方案
<el-table-column label="操作" width="100" align="center" fixed="right">
<template slot-scope="scope">
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除"
:disabled="scope.row.childList != undefined && scope.row.childList.size != 0"/>
</template>
</el-table-column>