Last active
March 29, 2021 12:24
-
-
Save bhushan/2fdbfed632cfd79cb6d40b12a85e8b9f to your computer and use it in GitHub Desktop.
Reusable Vue Components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
🗃️ Graphs in Vue using Chart.js | |
<template> | |
<canvas | |
ref="canvas" | |
class="p-4" | |
></canvas> | |
</template> | |
<script> | |
import Chart from 'chart.js'; | |
export default { | |
name: 'Graph', | |
props: { | |
labels: { | |
type: Array, | |
default: () => [], | |
}, | |
type: { | |
type: String, | |
default: 'line', | |
validator: (value) => { | |
return [ | |
'pie', | |
'bar', | |
'line', | |
'radar', | |
'doughnut', | |
'polarArea', | |
].includes(value); | |
}, | |
}, | |
datasets: { | |
type: Array, | |
default: () => [], | |
validator: (items) => { | |
let isValid = true; | |
for (let i = 0; i < items.length; i++) { | |
if (!('label' in items[i]) || !('data' in items[i])) { | |
isValid = false; | |
break; | |
} | |
} | |
return isValid; | |
}, | |
}, | |
options: { | |
type: Object, | |
default: () => { | |
return { | |
responsive: true, | |
}; | |
}, | |
}, | |
}, | |
data () { | |
return { | |
chart: null, | |
}; | |
}, | |
mounted () { | |
this.$nextTick(function () { | |
this.chart = new Chart(this.$refs.canvas.getContext('2d'), { | |
type: this.type, | |
data: { | |
labels: this.labels, | |
datasets: this.datasets, | |
}, | |
options: this.options, | |
}); | |
}); | |
}, | |
beforeDestroy () { | |
this.chart.destroy(); | |
}, | |
}; | |
</script> | |
//usage | |
<template> | |
<div> | |
<Graph | |
:labels="labels" | |
:datasets="datasets" | |
/> | |
<Graph | |
type="bar" | |
:labels="labels" | |
:datasets="datasets" | |
/> | |
<Graph | |
type="radar" | |
:labels="labels" | |
:datasets="datasets" | |
/> | |
<Graph | |
type="pie" | |
:labels="labels" | |
:datasets="datasets" | |
/> | |
<Graph | |
type="doughnut" | |
:labels="labels" | |
:datasets="datasets" | |
/> | |
<Graph | |
type="polarArea" | |
:labels="labels" | |
:datasets="datasets" | |
/> | |
</div> | |
</template> | |
<script> | |
export default { | |
name: 'DashboardPage', | |
data () { | |
return { | |
labels: ['Jan', 'Feb', 'March'], | |
datasets: [ | |
{ | |
label: '2020', | |
data: [10, 20, 30], | |
backgroundColor: 'rgb(255, 0, 0, 0.4)', | |
}, | |
{ | |
label: '2021', | |
data: [12, 22, 35], | |
backgroundColor: 'rgb(0, 255, 0, 0.4)', | |
}, | |
{ | |
label: '2022', | |
data: [1, 2, 5], | |
backgroundColor: 'rgba(0, 0, 255, 0.4)', | |
}, | |
], | |
}; | |
}, | |
}; | |
</script> | |
@rckstrbhushan | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment