Example 1 · Dynamic Line Chart
Use Case: Initialize Chart.js on mount, update on data changes, and clean it up on unmount.
Library: Chart.js
// Keep the Chart.js instance in $ctx.userData (Proxy-free, auto-cleanup) methods: { initLineChart($ctx) { const ctx = $ctx.element.querySelector('#lineChart').getContext('2d'); $ctx.userData.set('chart', new Chart(ctx, { type: 'line', data: { /* ... */ }, options: { responsive: true, maintainAspectRatio: false } })); }, updateLineChart($ctx) { const chart = $ctx.userData.get('chart'); // Spread reactive arrays into plain arrays before handing them to Chart.js chart.data.datasets[0].data = [...this.lineDataPoints]; chart.update(); }, destroyLineChart($ctx) { $ctx.userData.get('chart')?.destroy(); } }
Example 2 · Bar Chart with Statistics
Use Case: Display computed statistics alongside a dynamic bar chart.
{{ totalSales }}
Total Sales
{{ averageSales }}
Average
{{ maxSales }}
Maximum
// Computed properties work seamlessly with charts computed: { totalSales() { return this.salesData.reduce((a, b) => a + b, 0); }, averageSales() { return Math.round(this.totalSales / this.salesData.length); } }
Example 3 · Responsive Doughnut Chart
Use Case: Category distribution visualization with automatic updates.
// Responsive chart configuration options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { position: 'bottom' } } }
📦 Installation
Include Chart.js via CDN or npm:
<!-- Via CDN --> <script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script> // Via npm npm install chart.js