Chart.js 3 for Vue 2 and Vue 3
This package is a rewrite of vue-chartjs for Chart.js 3, but written in Typescript with vue-demi and Vue Composition API.
Installation
Important notes
Using with Vue 3 or Vue 2
This package works with version 2.x and 3.x of Vue.
- Vue 3 works out-of-the-box
- Vue 2 requires
@vue/composition-api
package to also be installed, to provide Vue 3's Composition API features likeref, defineComponent, computed, reactive
.
Chart.js (v3)
Chart.js v3 is now tree-shakable, so make sure to import and register the chart components you need. See Chart.js API for all available imports.
Learn more about Chart.js tree-shaking
For example, if you want to create a Doughnut chart and tree-shake the unused other components, it might look like this:
Or if you want all components of Chart.js (but lose the benefits of tree-shaking), use this:
Unlike vue-chartjs
, there is no need to re-create each component with mixins and reactive props, etc. with this package. Thanks to @vue/composition-api
, all of this is possible just by importing the corresponding component.
(Thanks to @nwittwer for upgraded notes)
Usage with Nuxt SSR
- Create a plugin in
<srcDir>/plugins/chartjs.js
- Then register it in your
nuxt.config.[js|ts]
Just it case, wrap your component inside client-only
.
Usage and docs
All components props
Prop | Type | Default |
---|---|---|
'chartData' | ChartJs.ChartData<TType> |
|
'options' | ChartJs.ChartOptions<TType> |
|
'plugins' | ChartJs.Plugin[] | |
'cssClasses' | string | |
'width' | number | 400 |
'height' | number | 400 |
'onChartRender' | (chartInstance: Chart) => void | |
'onChartUpdate' | (chartInstance: Chart) => void | |
'onChartDestroy' | () => void | |
'onLabelsUpdate' | () => void |
Data accessible by reference
Prop | Type |
---|---|
'chartInstance' | Chart<TType> |
'canvasRef' | HtmlCanvasElement |
'renderChart' | () => void |
Events emitted by all components
Event | Payload |
---|---|
'chart:render' | chartInstance: Chart |
'chart:update' | chartInstance: Chart |
'chart:destroy' | - |
'labels:update' | - |
Exemple with static data
Accessing Canvas Ref and ChartInstance
Exemple with reactive data, options, events and tree shaking
Helper types for Typescripts users
ExtractComponentData<T>
This component is useful if you want to access the Chart component ref.
Ex:
ExtractComponentProps<T>
This type will extracts prop types from the component if you want to type your v-bind
.
Ex:
Supporting plugins
You can use defineChartComponent
to create ChartJs plugins components
Exemple:
If you are using Typescript, you have to augment the interface ChartTypeRegistry
from chart.js
manually.
The plugins for Chart.js are usually typed, but if they aren't you can do it manually
(Exemple taken from chartjs-chart-matrix)