今天遇到一个很讨人厌的问题,
this.tChartInstance = echarts.init(document.getElementById(‘ChartDom’), null, {
width: 700,
height: 500
});
一直报Uncaught TypeError: Cannot read property ‘getAttribute’ of null错
然后发现console.log(‘dom’,document.getElementById(‘ChartDom’))打印结果是null,
就添加了延时
setTimeout(() => {// console.log('dom',document.getElementById('ChartDom'))this.tChartInstance = echarts.init(document.getElementById('ChartDom'), null, {width: 700,height: 500});this.tChartInstance .setOption(ringChartOption);
}, 0);
console.log(‘dom’,document.getElementById(‘ChartDom’))输出还是null
强制刷新会报:this.$forceUpdated is not a function
桥豆麻袋…由于这个echart放在一个dialog里面,但这个dialog根本没有打开,虽然打印this.reasonSortDialog结果确实是true,但是没有显示
item.instance.on('click', async (params) => {this.reasonSortDialog = true// console.log('打开模态框',this.reasonSortDialog)setTimeout(() => {// console.log('dom',document.getElementById('ChartDom'))this.tChartInstance = echarts.init(document.getElementById('ChartDom'), null, {width: 700,height: 500});this.tChartInstance.setOption(ringChartOption);}, 0);
});
so……让我们把问题聚焦到this.reasonSortDialog = true,
果然,console.log(this)发现这里的this指向的不是vue实例,而是里面的echart,所以他并不知道reasonSortDialog是个模态框,强制更新也会报错
解决方式:
const vue = {data() {},computed: {},watch: {},mounted() {},methods: {initCharts() {......const vue = this......item.instance.on('click', async (params) => {vue.reasonSortDialog = truesetTimeout(() => {this.tChartInstance= echarts.init(document.getElementById('ChartDom'), null, {width: 700,height: 500});this.tChartInstance.setOption(ringChartOption);}, 0);});......},}
}
export default vue
这样一来,用vue指向export default,就不会跟内部的this指向混淆啦
这里是vue2,vue3不会出现指向性问题
题外话,当今时代,要一个人从另一个人的世界里消失非常简单