教程 chartjs tutorial

在 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>
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Vue 中使用 Chart.js 示例</title> <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js&quot;&gt;&lt;/script&gt; <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
}

</style> </head>

<body> <div id="app"> <canvas id="vueChart" width="600" height="400"></canvas> </div> <script> (function () { const { createApp, onMounted, ref } = Vue;

  createApp({
    setup() {
      const chartRef = ref(null);
      let chartInstance = null;

      onMounted(() =&gt; {
        const ctx = document.getElementById('vueChart').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 }
            }
          }
        });
      });
    }
  }).mount('#app');
})();

</script> </body>

</html>