Search code examples
javascriptvue.jsvuejs3bootstrap-vueapexcharts

How to populate text are on click using vue apex charts dataPointIndex


I'm attempting populate a text area onclick from Apex chart. In the below code pen you can click on the bar and it generates an alert with the value from the chart. I would like to get that value and place it on the screen using b-card container instead of the alert. Should I use double curly braces for data binding instead of getElementById?

{{data}}

Method that returns data from apex chart

getAlertData(event, chartContext, config){
   var data = [];
   data = this.series[0].data[config.dataPointIndex]
   return data
}

https://codepen.io/tone373/pen/dyajwpa?editors=1011


Solution

  • With Vue, you should not use document interface functions such as getElementById if you can avoid it. Yes, use text interpolation with double curly braces, which is the "Vue way" of doing this. Your codepen's problem is two-fold

    One, you're trying to display {{data}} but you have no data variable. The data option which looks like

    data() {
      return {
       ...
      }
    }
    

    Returns variables you can directly use in your HTML with {{}}. A variable called "data" inside the data option is not a great name choice, but it's up to you... I would name it maybe "cardText". Then assign the value it should display in your click method, and display this variable in your HTML with the {{}} syntax.

      data() {
        return {
          chart: {},        
          series: [],
          chartOptions: {}, 
          cardText: ''
        }
      },
    
    ...
    
      selectBar(event, chartContext, config) {
        this.cardText = this.series[0].data[config.dataPointIndex]
      }
    
    <div>{{ cardText }}</div>
    

    Second problem, is you're trying to display this data outside of your Vue instance. Notice how you create the Vue instance with

    new Vue({
        el: "#app",
        ...
    })
    

    The #app is the element the Vue instance attaches to. Vue only has direct control over code inside this element, but you're trying to display {{data}} outside of it within a <b-card> element. You just need to move this code to be inside of <div id="app">

    updated codepen

    I used another <div> instead of <b-card> because your codepen does not include the library to make b-card work.

    I'll add that all the above information can be learned from reading the official Vue documentation. If you haven't read or consulted it, it's very well written and will help you learn the Vue framework better than almost any other resource.