vue-chart-3

website·Indexed 29 days ago

https://vue-chart-3.netlify.app/

A rewrite of vue-chartjs for Chart.js 4, providing Vue 3 components and fully typed hooks. It supports Vite.js, Nuxt 3, and Nuxt 2 with SSR and Composition API, offering reactive data updates, programmatic event triggers, and TypeScript integration.

Tokens
3.9K
Snippets
20
Records
23
Agent score
75%

What's inside vue-chart-3

  1. Simplify chart configuration using vue-chart-3 hooks

    vue-chart-3 provides fully typed hooks (currently in alpha) that simplify the usage of chart components by providing shortcuts for props and refs. Each chart component has a corresponding hook (e.g., BarChart uses useBarChart). The hook returns xxxChartProps for binding to the component, xxxChartRef for accessing the chart instance, and an update function for manual updates.
    import { defineComponent } from 'vue';
    import { useBarChart, BarChart } from 'vue-chart-3';
    
    export default defineComponent({
      setup() {
        const { barChartProps, barChartRef, update } = useBarChart({
          chartData: { /* your data */ },
          plugins: []
        });
    
        return { barChartProps, barChartRef };
      }
    });

    <!-- In template --> <BarChart v-bind="barChartProps" />

  2. Render a chart using vue-chart-3 components

    To render a chart, import the specific chart component (e.g., DoughnutChart) from vue-chart-3. Because vue-chart-3 is a wrapper around Chart.js, you must also import Chart and registerables from chart.js and call Chart.register(...registerables) to ensure all chart types and elements are available globally in your application.
    <template>
      <DoughnutChart :chartData="testData" />
    </template>
    
    <script lang="ts">
    import { defineComponent } from 'vue';
    import { DoughnutChart } from 'vue-chart-3';
    import { Chart, registerables } from 'chart.js';
    
    // Required to initialize Chart.js components
    Chart.register(...registerables);
    
    export default defineComponent({
      name: 'Home',
      components: { DoughnutChart },
      setup() {
        const testData = {
          labels: ['Paris', 'Nîmes', 'Toulon', 'Perpignan', 'Autre'],
          datasets: [
            {
              data: [30, 40, 60, 70, 5],
              backgroundColor: ['#77CEFF', '#0079AF', '#123E6B', '#97B0C4', '#A5C8ED'],
            },
          ],
        };
    
        return { testData };
      },
    });
    </script>
  3. Update charts reactively using chart-data and options

    In vue-chart-3, chart components automatically trigger an update whenever the values passed to the :chartData and :options props change. To make a chart reactive, wrap the data in a Vue ref or computed property. When the source data is modified, the component will detect the change and refresh the chart visualization.
    <template>
      <div>
        <!-- Bind reactive data and options props -->
        <DoughnutChart ref="doughnutRef" :chartData="testData" :options="options" />
        <button @click="shuffleData">Shuffle</button>
      </div>
    </template>
    
    <script>
    import { shuffle } from 'lodash';
    import { computed, defineComponent, ref } from 'vue';
    import { DoughnutChart } from 'vue-chart-3';
    
    export default defineComponent({
      name: 'Home',
      components: { DoughnutChart },
      setup() {
        // 1. Define reactive source data
        const data = ref([30, 40, 60, 70, 5]);
        const doughnutRef = ref();
    
        // 2. Define reactive options
        const options = ref({
          responsive: true,
          plugins: {
            legend: { position: 'top' },
            title: { display: true, text: 'Chart.js Doughnut Chart' },
          },
        });
    
        // 3. Use a computed property to format data for the chart
        const testData = computed(() => ({
          labels: ['Paris', 'Nîmes', 'Toulon', 'Perpignan', 'Autre'],
          datasets: [
            {
              data: data.value,
              backgroundColor: ['#77CEFF', '#0079AF', '#123E6B', '#97B0C4', '#A5C8ED'],
            },
          ],
        }));
    
        // 4. Modifying the ref triggers the chart update
        function shuffleData() {
          data.value = shuffle(data.value);
        }
    
        return { testData, shuffleData, doughnutRef, options };
      },
    });
    </script>
  4. Create Vue components for Chart.js plugins using defineChartComponent

    Use the defineChartComponent function from vue-chart-3 to wrap a Chart.js plugin (such as a custom controller or element) into a reusable Vue component. You must first register the plugin's controller and elements with the global Chart object from chart.js before defining the component.
    import { Chart, registerables } from 'chart.js';
    import { defineChartComponent } from 'vue-chart-3';
    import { MatrixController, MatrixElement } from 'chartjs-chart-matrix';
    
    // Register the plugin components with Chart.js
    Chart.register(MatrixController, MatrixElement, ...registerables);
    
    // Create the Vue component
    // Arguments: (ComponentName, chartType)
    const Matrix = defineChartComponent('MatrixChart', 'matrix');
    
    // The 'Matrix' component can now be used in Vue templates
  5. Manually force update a ChartInstance in vue-chart-3

    To force an update of the ChartInstance, access the component via a template ref and call the update() helper function. This is useful for triggering a re-render when data changes that are not automatically detected or when specific chart state needs to be refreshed.
    <template>
      <DoughnutChart ref="doughnutRef" :chartData="testData" @chart:render="handleChartRender" />
    </template>
    
    <script>
    import { defineComponent, ref, onMounted } from 'vue';
    import { DoughnutChart } from 'vue-chart-3';
    
    export default defineComponent({
      name: 'Home',
      components: { DoughnutChart },
      setup() {
        const doughnutRef = ref();
    
        onMounted(() => {
          // Call the update helper function on the template ref
          doughnutRef.value.update();
        });
    
        return { doughnutRef };
      },
    });
    </script>
  6. Trigger programmatic plugin actions in vue-chart-3

    To call programmatic events or plugin actions (such as those provided by chartjs-plugin-zoom), access the chartInstance property on the chart's template ref. This provides direct access to the underlying Chart.js instance and its associated plugins.
    // Example: Resetting zoom using chartjs-plugin-zoom
    barChartRef.value.chartInstance.resetZoom();
  7. Use TypeScript with vue-chart-3 components

    vue-chart-3 components provide full TypeScript support for props. For the best developer experience and type-checking (including error highlighting), it is recommended to use the Volar extension in your IDE.
  8. Access the Chart.js instance and canvas reference in vue-chart-3

    The Chart.js chartInstance and canvasRef can be accessed in two ways: via a Vue template reference (ref) or through component events. This allows developers to call native Chart.js methods (such as toBase64Image()) directly on the instance.
    <template>
      <!-- Use ref to access the component instance -->
      <DoughnutChart 
        ref="doughnutRef" 
        :chartData="testData" 
        @chart:render="handleChartRender" 
      />
    </template>
    
    <script>
    import { defineComponent, ref, onMounted } from 'vue';
    import { DoughnutChart } from 'vue-chart-3';
    
    export default defineComponent({
      components: { DoughnutChart },
      setup() {
        const doughnutRef = ref();
    
        onMounted(() => {
          // Access the Chart.js instance via the ref
          const chartInstance = doughnutRef.value.chartInstance;
          console.log(chartInstance);
          
          // Example: Export chart to base64 image
          chartInstance.toBase64Image();
        });
    
        // The chart instance is also passed as an argument to events like @chart:render and @chart:update
        function handleChartRender(chart) {
          console.log('Chart instance from event:', chart);
        }
    
        return { testData, doughnutRef, handleChartRender };
      },
    });
    </script>
  9. Create a custom chart hook with defineChartHook

    When creating a custom chart component using defineChartComponent, you can also create a corresponding custom hook using defineChartHook to maintain the same developer experience as the built-in charts.
    import { defineComponent } from 'vue';
    import { defineChartComponent, defineChartHook } from 'vue-chart-3';
    
    const MatrixChart = defineChartComponent('matrix-chart', 'matrix');
    const useMatrixChart = defineChartHook('matrix');
    
    export default defineComponent({
      components: { MatrixChart },
      setup() {
        const { matrixChartProps, matrixChartRef } = useMatrixChart({
          chartData: {},
          plugins: []
        });
    
        return { matrixChartProps, matrixChartRef };
      }
    });
  10. Install vue-chart-3 and Chart.js

    To use vue-chart-3 in a Vue 3 project, you must install both the wrapper library and the core Chart.js library.
    npm i vue-chart-3 chart.js
    # or
    yarn add vue-chart-3 chart.js
    # or
    pnpm i vue-chart-3 chart.js
  11. Configure vue-chart-3 for Nuxt 3

    Because Chart.js requires client-side registration, you must create a Nuxt plugin to register Chart.js components. Create a file at <srcDir>/plugins/chartjs.client.ts. The .client.ts suffix ensures Nuxt 3 only executes this plugin on the client side.
    import { defineNuxtPlugin } from '#app';
    
    // Workaround because chart.js doesn't provide an default export
    import * as ChartJs from 'chart.js';
    const { Chart, registerables } = ChartJs;
    
    export default defineNuxtPlugin(() => {
      Chart.register(...registerables);
    });