How to bind to Highcharts constructor/listen to CustomEvents from Vue component

蓝咒 提交于 2019-12-11 08:51:51

问题


This map exists inside of a Vue component and what I'm trying to do is use

this.$emit('somethingHappened', HighmapsEventObject)

mounted () {
  Highcharts.mapChart(this.$el, { 
    series: [{ 
      events: {
        click: () => { 

          in here 

        }
      } 
    }]
  })
}

as in

mounted () {
  Highcharts.mapChart(this.$el, { 
    series: [{ 
      events: {
        click: () => { 

          `this.$emit('somethingHappened', HighmapsEventObject)`

        }
      } 
    }]
  })
}

But obviously, this at this point, references the Highmap's this not the Vue component's this

so I've tried to do something like this:

mounted () {
  Highcharts.mapChart(this.$el, { 
    series: [{ 
      events: {
        click: (e) => { 

          this.$emit('somethingHappened', e)

        }
      } 
    }]
  }).bind(this)
}

But I get:

... default.a.mapChart(...).bind is not a function

and I can't figure out how to pass the Vue component's this to the highmaps constructor and Vue doesn't naturally listen to CustomEvents so I can't figure out how to dispatch the event in that callback so that Vue is aware that it happened.

mounted () {
  Highcharts.mapChart(this.$el, { 
    series: [{ 
      events: {
        click: (e) => { 
          let event = new CustomEvent('mapclicked', {
            detail: e
          })
          e.target.dispatch(event)
        }
      } 
    }]
  })
}

So my question, at long last, is how do I either a: listen for CustomEvents in Vue, or b: bind Vue's this to a Highmaps constructor?

Thanks SO


回答1:


3 options as far as i can see, you can use the infamous "that" variable

mounted () {
  const that = this;
  Highcharts.mapChart(this.$el, { 
    series: [{ 
      events: {
        click: () => { 
          that.$emit('somethingHappened', HighmapsEventObject)
        }
      } 
    }]
  })
}

you can create a function directly:

mounted () {
  const something = (HighmapsEventObject) => { this.$emit('somethingHappened', HighmapsEventObject); };
  Highcharts.mapChart(this.$el, { 
    series: [{ 
      events: {
        click: () => { 
           something(HighmapsEventObject);
        }
      } 
    }]
  })
}

Or you can use an event bus https://alligator.io/vuejs/global-event-bus/ but that sounds like an overkill.

Finally you can try (if you aren't already) the highchart vue plugin: https://github.com/weizhenye/vue-highcharts



来源:https://stackoverflow.com/questions/43824976/how-to-bind-to-highcharts-constructor-listen-to-customevents-from-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!