vue导出excel失败报错TypeError: Cannot read properties of null (reading 'removeChild')

405 阅读1分钟

问题描述:

前几天碰到一个问题,一直报这个错误TypeError: Cannot read properties of null (reading 'removeChild'),就是找不到原因。

通常报TypeError: Cannot read properties of null 错误的一般都是没有找到对应的属性或者方法。

解决思路:

我起初以为是我代码执行顺序的问题,改来改去还是一直报这个错误,后面看代码,发现是 getElementById('elTable')这里的问题,是因为我页面的表格中没有给它赋值一个id导致的问题,加上之后就可以。

async download() {
  this.downloadLoading = true
  this.size = 9999
  await this.init()
  this.$nextTick(() => {
    import('@/vendor/Export2Excel').then(excel => {
      let table = null
      const fix = document.querySelector('.el-table__fixed')
      if (fix) { // 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去
        table = document.getElementById('elTable').removeChild(fix)
        document.getElementById('elTable').appendChild(fix)
      } else {
        table = document.getElementById('elTable')
      }
      var arr = document.getElementsByClassName('gutter')
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] != null) {
          arr[i].parentNode.removeChild(arr[i])
        }
      }
      const sheetName = '委员履职情况表'
      excel.exportExcelMethod(table, sheetName, sheetName)
      this.downloadLoading = false
      this.size = 10
    })
  })
}
<el-table v-if="isBanan==false" id="elTable" ref="table" v-loading="loading" :header-cell-style="{background:'#F3F3F3'}" :data="data" style="width: 100%;">
  <el-table-column type="index" label="序号" align="center" width="50" fixed="left" />
    <template slot-scope="scope">
      <span style="cursor:pointer;color: blue; text-decoration: underline" @click="handleDetail(scope.row)">
        {{ scope.row.userName }}
      </span>
    </template>
  </el-table-column>
  <el-table-column v-for="item in limitTwoData" :key="item.id" :prop="item.id" :label="item.name" align="center">
    <el-table-column v-for="i in item.children" :key="i.id" :label="i.name" :prop="i.id" align="center" min-width="100" show-overflow-tooltip>
      <el-table-column v-for="ic in i.children" :key="ic.id" :label="ic.name" :prop="ic.id" align="center" min-width="100" show-overflow-tooltip />
    </el-table-column>
  </el-table-column>
  <el-table-column v-for="item in lastData" :key="item.id" :prop="item.id" :label="item.name" align="center">
    <el-table-column v-for="i in item.children" :key="i.id" :prop="i.id" :label="i.name" align="center" min-width="100" show-overflow-tooltip>
      <el-table-column v-for="ic in i.children" :key="ic.id" :prop="ic.id" :label="ic.name" align="center" min-width="100" show-overflow-tooltip />
    </el-table-column>
  </el-table-column>
</el-table>