主题
在 Vue 中使用
在现代前端开发中,Vue 是常用的框架。可以在 Vue 组件内引入 Chart.js,并通过响应式数据驱动图表更新,充分利用 Vue 的生命周期钩子管理图表实例。
下面示例展示一个简单的 Vue 3 组件,使用 onMounted
创建图表,ref
管理 canvas 元素。
vue
<template>
<canvas ref="chartRef" width="600" height="400"></canvas>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import Chart from 'chart.js/auto'
const chartRef = ref(null)
let chartInstance = null
onMounted(() => {
const ctx = chartRef.value.getContext('2d')
chartInstance = new Chart(ctx, {
type: 'line',
data: {
labels: ['一月', '二月', '三月', '四月', '五月', '六月', '七月'],
datasets: [{
label: '示例数据',
data: [65, 59, 80, 81, 56, 55, 40],
borderColor: 'rgb(75, 192, 192)',
fill: false,
tension: 0.1
}]
},
options: {
responsive: true,
plugins: {
legend: { display: true }
}
}
})
})
onBeforeUnmount(() => {
if (chartInstance) {
chartInstance.destroy()
}
})
</script>
loading