创建Vue2项目,引入chart.js,并生成柱形图、折线图、饼图
首先,确保你已经安装了Vue CLI。如果没有安装,可以通过以下命令安装:
npm install -g @vue/cli
# 或者
yarn global add @vue/cli
然后,创建一个新的Vue2项目:
vue create my-chart-app
# 选择 Vue 2
进入项目目录:
cd my-chart-app
安装Chart.js:
npm install chart.js
# 或者
yarn add chart.js
在Vue组件中使用Chart.js绘制图表。以下是一个简单的示例,展示了如何创建柱形图、折线图和饼图:
<template>
<div>
<canvas id="bar-chart"></canvas>
<canvas id="line-chart"></canvas>
<canvas id="pie-chart"></canvas>
</div>
</template>
<script>
import Chart from 'chart.js/auto';
export default {
mounted() {
this.createBarChart();
this.createLineChart();
this.createPieChart();
},
methods: {
createBarChart() {
const ctx = document.getElementById('bar-chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'palette.primary.main',
borderColor: 'palette.primary.dark',
borderWidth: 1,
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
},
createLineChart() {
const ctx = document.getElementById('line-chart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55],
fill: false,
borderColor: 'palette.primary.main',
tension: 0.1
}]
}
});
},
createPieChart() {
const ctx = document.getElementById('pie-chart').getContext('2d');
new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'My First Dataset',
data: [300, 50, 100],
backgroundColor: ['palette.primary.main', 'palette.secondary.main', 'palette.error.main'],
}
评论已关闭