vue-google-charts

repository·master·Indexed 19 days ago

https://github.com/devstark-com/vue-google-charts

A reactive Vue.js wrapper for the Google Charts library supporting Vue 2 and Vue 3. It provides the GChart component for simplified chart integration, handling the Google Charts loader and offering reactive data binding for chart data, types, and options. Features include automatic data processing via visualization.arrayToDataTable, responsive behavior with configurable resizeDebounce, and a loadGoogleCharts function for manual library loading.

Tokens
6.1K
Snippets
27
Records
30
Agent score
63%

What's inside vue-google-charts

  1. Handle chart ready and events

    master

    The GChart component emits a @ready event when the Google Charts library has loaded and the chart object is initialized. This event provides access to both the GoogleChartWrapper instance and the underlying Google Charts API.

    Additionally, you can pass event listeners via the events prop to listen to specific Google Visualization events (like select, ready, or error) directly on the chart instance.

    <template>
      <GChart
        type="ColumnChart"
        :data="data"
        :events="chartEvents"
        @ready="handleReady"
      />
    </template>
    
    <script setup>
    import { GChart } from 'vue-google-charts';
    
    const data = [['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2]];
    
    const chartEvents = {
      select: (event) => {
        console.log('User selected a data point');
      }
    };
    
    const handleReady = (chartObject, api) => {
      // chartObject is the GoogleChartWrapper
      // api is the loaded GoogleViz instance
      console.log('Chart initialized');
    };
    </script>
  2. Define GoogleDataTable columns and data cells

    master

    Data for Google Charts is structured using GoogleDataTable or GoogleDataView.

    Columns (GoogleDataTableColumn): Columns can be defined as a simple string (the label) or an object specifying:

    • type: One of string, number, boolean, date, datetime, or timeofday.
    • label: The display label.
    • role: A GoogleDataTableColumnRoleType (e.g., 'annotation', 'tooltip', 'style', 'interval').
    • id: A unique identifier.

    Cells (GoogleDataTableCell): Each cell in a row can be a primitive value or an object providing:

    • v: The actual value.
    • f: The formatted string value for display.
    • p: Custom properties.
    export type GoogleDataTableColumn =
      | { 
          type: GoogleDataTableColumnType; 
          label?: string; 
          role?: GoogleDataTableColumnRoleType; 
          pattern?: string; 
          p?: {}; 
          id?: string; 
        }
      | string;
    
    export type GoogleDataTableCell =
      | { v?: any; f?: string; p?: {} }
      | string
      | number
      | boolean
      | Date;
  3. Link the plugin to another project for local development

    master

    To test changes made to the plugin in a separate project without publishing to npm, use npm link:

    1. In the plugin folder: npm link

    2. In the consumer project folder: npm link vue-google-charts

    # In plugin folder
    npm link
    
    # In consumer project folder
    npm link vue-google-charts
  4. Handle chart events in Vue

    master

    You can listen to Google Chart events by passing a chartEvents object to your component's data. The keys in this object should be the event names (e.g., 'select'), and the values should be your handler functions.

    export default {
      data() {
        return {
          chartEvents: {
            'select': () => {
              // handle event here
            }
          }
        }
      }
    }
  5. Use the GChart component

    master

    The GChart component is a reactive wrapper for Google Charts. It automatically handles loading the Google Charts library and re-draws the chart whenever the data or options props change.

    Key features:

    • Automatic Data Processing: If you provide a 2D array to the :data prop, it is automatically processed using Google's visualization.arrayToDataTable function.
    • Reactive Binding: Charts update automatically when bound data or options change.
    • Google Charts Compatibility: The type prop accepts any valid Google Chart type (e.g., ColumnChart, PieChart, Map).
    <GChart
      type="ColumnChart"
      :data="chartData"
      :options="chartOptions"
    />
  6. Develop and build the vue-google-charts plugin

    master

    If you are contributing to or developing the vue-google-charts plugin itself, use the following commands:

    • Install dependencies: npm i
    • Watch and compile (Development): npm run dev (runs webpack in watching mode, outputs to dist/).
    • Manual build (Production): npm run build (builds the plugin into the dist/ folder in production mode).
    npm i
    npm run dev
    npm run build
  7. Install vue-google-charts as a Vue plugin

    master

    To use the GChart component globally in your Vue application, use the install function or the default export. This registers the GChart component so it can be used in any template without local registration.

    import { createApp } from 'vue';
    import VueGoogleCharts from 'vue-google-charts';
    
    const app = createApp({});
    app.use(VueGoogleCharts);
  8. Use the @ready event for custom chart drawing

    master

    If you need to perform highly custom operations, such as fetching data from a Google Spreadsheet and then drawing the chart manually, use the @ready event listener. This event provides access to both the chart instance and the google visualization object.

    <GChart
      type="ColumnChart"
      @ready="onChartReady"
    />
    
    <script>
    export default {
      methods: {
        onChartReady(chart, google) {
          const query = new google.visualization.Query('https://url-to-spreadsheet...');
          query.send(response => {
            const options = { /* some custom options */ };
            const data = response.getDataTable();
            chart.draw(data, options);
          })
        }
      }
    }
    </script>
  9. Register vue-google-charts globally or locally

    master

    You can install the plugin globally to use it throughout your application, or import the GChart component locally within specific components.

    Global installation (as a plugin):

    import Vue from 'vue'
    import VueGoogleCharts from 'vue-google-charts'
    
    Vue.use(VueGoogleCharts)

    Local installation (in a component):

    import { GChart } from 'vue-google-charts'
    
    export default {
      components: {
        GChart
      }
    }