Hooks

Guide

WARNING

Hooks are still in alpha

vue-chart-3 also provides fully typed hooks compatible with Vue 2 and Vue 3 using vue-demi.

They are not mandatory, but they simplify the usage of chart components.

Each component has its corresponding hooks. Ex: Barchart will have useBarChart.

Usage

Using the useXXXChart will clean up your code as it provides a shortcut for props and ref

Declaring it give you access to xxxChartProps and xxxChartRef.

For BarChart you can import useBarChart from vue-chart-3 and use it like this

export default defineComponent({
  ...,
  setup() {
    const { barChartProps, barChartRef, update } = useBarChart({
      chartData: {}, //...
      plugins: []
    });

    return { barChartProps, barChartRef }
  }
})

1
2
3
4
5
6
7
8
9
10
11
12

Then you can use the barChartProps to fill the props of the component

<BarChart v-bind="barChartProps" />
1

Manual update

This hook also returns a helper function to manually update the ChartInstance

const { barChartProps, barChartRef, update } = useBarChart({...})
1

Custom hook

If you have created a custom Chart component, you can also create your custom hook

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 }
  }
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Usage with render function

Usage with render function is supported, with just a parameter. The reason is that in templates, Vue needs a string ref (ex: ref='inputRef'), but in render functions, it needs the ref accessor (ex: ref={inputRef})

export default defineComponent({
  ...,
  setup() {
    const { barChartProps, barChartRef } = useBarChart({
      chartData: {},
      plugins: [],
      jsx: true // <----
    });

    return () => (
      <BarChart {...barChartProps.value} />
    )
  }
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15