- 物料准备:
- 需求描述:在el-table中使用el-popover,点击某行的操作按钮,打开弹窗,渲染echarts饼状图,饼图数据从接口动态获取。
- 实现:
- 问题1:开始渲染饼图时,canvas为正方形,始终无法调整width/height,且饼图无数据。
- 原因:popover弹窗还没完全展开时,Echarts图表的canvas画布已经开始渲染,但是这时获取不到popover弹窗的长宽,所以canvas画布渲染出现问题。
- 解决:在@after-enter中获取接口数据,初始化绘图。after-enter方法是popover显示动画播放完毕后触发,此时已经可以获取到弹窗的width/height,canvas画布和图表渲染都没有问题。
<el-table> <el-table-column label="查看接口失败原因"> <template slot-scope="scope"> <el-popover placement="bottom" title="失败原因分析" width="200" trigger="click"> <!-- pieChart 容器 --> <div :ref="'pieChart'+scope.row.apiId" style="width: 400px; height: 300px;"></div> <el-button slot="reference" @click="getFailReason(scope.row)" type="text">查看</el-button> </el-popover> </template> </el-table-column> </el-table>
getFailReason (row) { $api.getFailReason(row.apiId).then(res => { initPieChart(res.data, row.apiId) }).catch(err => { $errorHandler('TYPE_API', err) }) }
- 问题2: 在多行表格中,只有点击最后一行操作时,才能渲染图标,其余都不渲染。
- 原因:在渲染图标获取canvas容器时,用于ref写死了,相同ref存在后覆盖问题,所以只能获取到最后一个容器。
- 解决:由于表格每一行一定有一个唯一的key,将这个key和ref进行绑定即可。
<el-table> <el-table-column label="查看接口失败原因"> <template slot-scope="scope"> <el-popover placement="bottom" title="失败原因分析" width="200" trigger="click"> <!-- pieChart 容器 --> <div :ref="'pieChart'+scope.row.apiId" style="width: 400px; height: 300px;"></div> <el-button slot="reference" @click="getFailReason(scope.row)" type="text">查看</el-button> </el-popover> </template> </el-table-column> </el-table>
initPieChart (apiId, data) { // 获取容器 const dom = this.$refs[`pieChart${apiId}`] // ... } ```
- 问题3:找到当前打开的popover弹框,手动关闭。
- 解决:为el-popover绑定唯一的ref,思路和问题2的解决一样,获取到该popover组件后,调用组件中相关api即可。
<el-popover placement="bottom" title="失败原因分析" width="200" trigger="click"> <!-- 关闭按钮 --> <div @click="closePopover(scope.row.apiId)"><i class="el-icon-close"></i></div> <div :ref="'pieChart'+scope.row.apiId" style="width: 400px; height: 300px;"></div> <el-button slot="reference" @click="getFailReason(scope.row)" type="text">查看</el-button> </el-popover>
closePopover (apiId) { // doClose是我获取到该组件之后,打印其内容找到的,也有对应的打开方法/属性 this.$refs[`popoverRef${id}`].doClose() }
- 问题1:开始渲染饼图时,canvas为正方形,始终无法调整width/height,且饼图无数据。
- 效果展示
在el-popover弹窗中根据接口数据动态渲染echarts饼图
最新推荐文章于 2025-03-24 17:26:10 发布