在 Vue 中使用
在现代前端开发中,Vue 是常用的框架。可以在 Vue 组件内引入 Chart.js,并通过响应式数据驱动图表更新,充分利用 Vue 的生命周期钩子管理图表实例。
下面示例展示一个简单的 Vue 3 组件,使用 onMounted 创建图表,ref 管理 canvas 元素。
<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"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<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(() => {
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>
相关内容
- 什么是 Chart.js? Chart.js 是一个简单易用且功能强大的 JavaScript 图表库,支持多种常见图表类型,帮助开发者快速创建美观且响应式的数据可视化效果,适合初学者和专...
- 安装与引入 介绍如何在项目中安装和引入 Chart.js,包括通过 CDN 快速使用和通过 npm 安装到前端构建环境的多种方式,帮助快速搭建图表开发环境。
- 基本结构与初始化 讲解如何创建图表的基本结构与初始化流程,包括配置画布、准备数据和实例化图表的步骤,帮助快速搭建图表展示。
- 示例:折线图 通过示例讲解如何创建折线图,涵盖数据配置、样式设置和基本交互,帮助快速掌握折线图的绘制技巧。
- 折线图 Line 介绍如何使用 Chart.js 创建折线图,详细讲解数据配置、样式调整及交互功能,帮助快速制作趋势图表。
- 柱状图 Bar 介绍如何使用 Chart.js 创建柱状图,详细讲解数据配置、颜色设置及图表样式,帮助快速绘制直观的条形数据展示。