1. Requirement: vue mobile echarts clicks outside the chart to hide the tooltip
methods:{
//监听鼠标点击的位置,清除tooltip
handleChartClick(e) {
// 判断点击的位置是否在图表上
const { left, top, width, height } = document
.getElementById(this.id)
.getBoundingClientRect();
const x = e.clientX;
const y = e.clientY;
if (x < left || x > left + width || y < top || y > top + height) {
// 隐藏tooltip
this.myChart.dispatchAction({ type: "hideTip" });
}
},
},
2. Listen to the click event in mouted and remove the event in beforeDestory
mounted() {
// 监听点击事件隐藏tooltip
document.addEventListener("click", this.handleChartClick, true);
},
beforeDestroy() {
// 解绑点击事件
document.removeEventListener("click", this.handleChartClick, true);
},
The good guy reported an error, and the error was only reported after jumping to the next page and clicking on the page:
Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null at VueComponent.handleChartClick;
I searched around but couldn't find a solution. Then I saw the key field: VueComponent. I opened the Google debugging tool and found that the component was not destroyed and was in an inactive state. Then I remembered to write the keepAlive cache page. . . TT
3. Therefore, the click event needs to be removed in the deactivated state:
deactivated(){
//因为组件缓存,所以也要解绑点击事件
document.removeEventListener("click", this.handleChartClick, true);
}