在开发一个后台的时候,我们需要经常用到各种图表展示数据,然后数据更加直观,同时也让自己的项目逼格更高。今天我们就用Vue3+Chart.js组件来展示数据。
我们在已经安装了Vue3的基础上来安装Chart.js.
Chart.js官网地址:https://www.chartjs.org/
一、安装Chart.js
npm install chart.js
二、在vue组件中使用
html代码:
<div class="card-content-image">
<canvas id="planetChart" width="100%" height="380"></canvas>
</div>
script代码
<script setup>
import Chart from 'chart.js/auto';
import {onMounted} from "vue";
const data = {
labels: ['22-10-01', '22-10-02', '22-10-03', '22-10-04', '22-10-05', '22-10-06', '22-10-07', '22-10-08', '22-10-09', '22-10-10', '22-10-11', '22-10-12'],
datasets: [
{
label: 'Dataset 1',
data: [23, 42, 35, 27, 43, 22, 17, 31, 22, 22, 102, 16],
},
{
label: 'Dataset 2',
data: [213, 42, 35, 27, 43, 22, 17, 31, 22, 22, 12, 16],
}
]
}
onMounted(() => {
const ctx = document.getElementById('planetChart');
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: '7日数组走势图'
}
}
},
});
})
</script>
展示结果:
注意
如果提示 chart: can't acquire context from the given item 是组件还没有加载完成导致的,把执行放入 onMounted 钩子函数中就可以了。
更多的配置,比如颜色,背景色等参考官网配置文档:https://www.chartjs.org/docs/latest/configuration/