Created
February 25, 2017 17:04
-
-
Save dammyammy/0905c562bfb157c31843d5d749c01a64 to your computer and use it in GitHub Desktop.
My Graph Vue Component Dependent on ChartJs, Axios, and My Color Generator
This file contains hidden or 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
<template> | |
<canvas ref="canvas"></canvas> | |
</template> | |
<script> | |
import Chart from 'chart.js'; | |
import ColorGenerator from '../core/ColorGenerator'; | |
export default Vue.extend({ | |
props: { | |
labels: { type: Array }, | |
type: { type: String, default: 'line' }, | |
title: { type: String, require: true }, | |
data: { require: true } | |
}, | |
data() { | |
return { chart: '' } | |
}, | |
mounted() { | |
this.$nextTick(function () { | |
this.render(this.data); | |
}) | |
}, | |
methods: { | |
getChartData(datasets = []) | |
{ | |
datasets.map(function (dataset) { | |
if(! dataset.hasOwnProperty('backgroundColor')) { | |
dataset.backgroundColor = (new ColorGenerator).grab(dataset.data.length) | |
} | |
if(! dataset.hasOwnProperty('label')) { | |
dataset.label = '' | |
} | |
return dataset; | |
}) | |
return { labels: this.labels, datasets }; | |
}, | |
isURL(data) { | |
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol | |
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name | |
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address | |
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path | |
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string | |
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator | |
return pattern.test(data); | |
}, | |
fetchDataFromURL(data){ | |
return axios.get(data).then(({ data }) => { this.render(data) }); | |
}, | |
getChartOptions() { | |
return { | |
responsive: true, | |
title: { | |
display: true, | |
text: this.title, | |
fontSize: 24, | |
}, | |
legend: { | |
display: true, | |
}, | |
scales: { | |
yAxes: [{ | |
ticks: { | |
beginAtZero: true | |
} | |
}], | |
xAxes: [] | |
} | |
}; | |
}, | |
render(datasets) { | |
if(this.isURL(datasets)) return this.fetchDataFromURL(datasets); | |
this.chart = new Chart(this.$refs.canvas.getContext("2d"), { | |
type: this.type, | |
data: this.getChartData(datasets), | |
options: this.getChartOptions() | |
}); | |
}, | |
reload() { | |
this.chart.destroy(); | |
this.fetchDataFromURL(this.data); | |
} | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment