今天在用element-ui写分页,在写分页逻辑的时候,使用slice()对数据进行分割时,出现了
Error in render: "TypeError: Cannot read properties of null (reading 'slice')"的报错
下面是我报错时的代码
data() {
return {
tableData:null,
total: null,
currentPage: 1,
pageSizes: [10, 20, 30, 40],
pageSize: 10
}
},
computed: {
getPageData() {
let getPageData;
getPageData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
return getPageData
}
},
问题原因:
当tableData不为空(null)时,不会报错,但是一旦后台数据的属性为空时,就会报错,那是因为一个空数据是没有长度的,没有length属性,也不能用slice()方法。
Error in render: "TypeError: Cannot read properties of null (reading 'slice')"
解决方法
- 方法1:
主动将tableData赋值为一个数组,其他不变就可解决报错问题
data() {
return {
tableData:[],
total: null,
currentPage: 1,
pageSizes: [10, 20, 30, 40],
pageSize: 10
}
},
computed: {
getPageData() {
let getPageData;
getPageData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
return getPageData
}
},
不便不便
- 方法2:
判断一下tableData的值是否为null,就可以顺利解决啦
data() {
return {
tableData:null,
total: null,
currentPage: 1,
pageSizes: [10, 20, 30, 40],
pageSize: 10
}
},
computed: {
getPageData() {
let getPageData;
this.tableData==null?getPageData=this.tableData:getPageData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize) */
return getPageData
}
},