Echarts OnClick 方法未到达 Vue 中的外部方法

Echarts OnClick Methods not reaching external methods in Vue

所以我用 Vue 应用程序实现了 Echarts,在其中一个图表上,我试图让项目被点击并将它传递回父组件,这样我就可以对它进行特定的计算。

'on click' 方法有效,我可以轻松地 console.log('params'),但是,出于某种原因,尝试访问它之外的任何其他功能是不可能的...

这是我的代码...

data() {
   return {
      myChart: null,
      selectedState: {}
   }
}.
mounted() {
   this.myChart = echarts.init(document.getElementById("geoMap"))

   this.myChart.on('click', function(params){
      // It will run the console.log with correct info, but the 
      // method is not reachable...
      console.log(params)
      this.setSelectedState(params)
   })
},

// Inside my vue script this is just a method to set the data for now...
methods: {
   setSelectedState(params){
      this.selectedState = params
   },
}

任何帮助都会很好!!谢谢!

你在监听图表事件时不在 Vue 组件上下文中,所以你必须将你的回调函数更改为箭头一来访问组件的 this :

this.myChart.on('click', params => {
  this.setSelectedState(params)
});
methods: {
  setSelectedState(params) {
    console.log(params);
    this.selectedState = params
  }
}

顺便说一句,您应该使用 ref 而不是让 div 和 document.getElementById 附上您的图表:

<div ref="geoMap"></div>
this.myChart = echarts.init(this.$refs.geoMap);