[[toc]]
Thank to the author of Using Chart.js with Vue.js [1].
Create a vue component.
- Change to directory of your vuepress project. For me:
cd /Users/mac/Github/way2ml
- Install
chart.js
by using this command.
npm install chart.js --save
- Create a
Draw.vue
file with following contents in directorydoc/.vuepress/components/
.
<template>
<div id="app">
<canvas id="planet-chart"></canvas>
</div>
</template>
<script>
import Chart from 'chart.js';
import planetChartData from './js/chart-data.js';
export default{
mounted() {
this.createChart('planet-chart', this.planetChartData);
},
data() {
return {
planetChartData: planetChartData,
}
},
methods:{
createChart(chartId, chartData) {
const ctx = document.getElementById(chartId);
const myChart = new Chart(ctx, {
type: chartData.type,
data: chartData.data,
options: chartData.options,
});
}
},
}
</script>
- Create a folder named
js
underdocs/vuepress/components/
. And create a file namedchart-data.js
underjs/
with the following content.
export const planetChartData = {
type: 'line',
data: {
labels: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'],
datasets: [
{ // one line graph
label: 'Number of Moons',
data: [0, 0, 1, 2, 67, 62, 27, 14],
backgroundColor: [
'rgba(54,73,93,.5)', // Blue
'rgba(54,73,93,.5)',
'rgba(54,73,93,.5)',
'rgba(54,73,93,.5)',
'rgba(54,73,93,.5)',
'rgba(54,73,93,.5)',
'rgba(54,73,93,.5)',
'rgba(54,73,93,.5)'
],
borderColor: [
'#36495d',
'#36495d',
'#36495d',
'#36495d',
'#36495d',
'#36495d',
'#36495d',
'#36495d',
],
borderWidth: 3
},
{ // another line graph
label: 'Planet Mass (x1,000 km)',
data: [4.8, 12.1, 12.7, 6.7, 139.8, 116.4, 50.7, 49.2],
backgroundColor: [
'rgba(71, 183,132,.5)', // Green
],
borderColor: [
'#47b784',
],
borderWidth: 3
}
]
},
options: {
responsive: true,
lineTension: 1,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
padding: 25,
}
}]
}
}
}
export default planetChartData;
At this point, I created my vue component called Draw.vue
.
Use component in Markdown file.
Just add this line into your markdown file, so you can plot.
<Draw/>
Have fun.
[1]: Using Chart.js with Vue.js. ↩︎