Skip to content

Commit 39365d5

Browse files
committed
refactor: add no dataset exception, clean code
1 parent 56990be commit 39365d5

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed

src/Chart.vue

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,36 @@ export default {
1212
plugins: Array
1313
},
1414
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
15-
data() {
15+
data () {
1616
return {
1717
chart: undefined
1818
}
1919
},
20+
watch: {
21+
chartConfig () {
22+
this.updateChart()
23+
}
24+
},
25+
mounted () {
26+
this.renderChart()
27+
},
28+
beforeDestroy () {
29+
this.destroyChart()
30+
},
2031
computed: {
21-
safeId() {
32+
safeId () {
2233
// as long as this._uid() works there is no need to generate the key
2334
const key = () => Math.random().toString(36).replace('0.', '')
2435
return '__safe_id__' + this._uid || key()
2536
},
26-
computedDatasets() {
37+
computedDatasets () {
2738
return this.datasets
2839
},
29-
computedLabels() {
40+
computedLabels () {
3041
if (this.labels && typeof this.labels !== 'string') {
3142
return this.labels
43+
} else if (!this.datasets || !this.datasets[0] || !this.datasets[0].data) {
44+
return []
3245
}
3346
const emptyLabels = Array(this.datasets[0].data.length).fill('')
3447
@@ -39,13 +52,13 @@ export default {
3952
}
4053
return emptyLabels
4154
},
42-
computedData() {
55+
computedData () {
4356
return {
4457
datasets: this.computedDatasets,
4558
labels: this.computedLabels
4659
}
4760
},
48-
customTooltips() {
61+
customTooltips () {
4962
if (this.options && this.options.tooltips) {
5063
return
5164
}
@@ -77,10 +90,10 @@ export default {
7790
}
7891
}
7992
},
80-
computedOptions() {
93+
computedOptions () {
8194
return Object.assign({}, this.options, this.customTooltips || {})
8295
},
83-
chartConfig() {
96+
chartConfig () {
8497
return {
8598
type: this.$options.type,
8699
data: this.computedData,
@@ -89,35 +102,24 @@ export default {
89102
}
90103
}
91104
},
92-
watch: {
93-
chartConfig() {
94-
this.updateChart()
95-
}
96-
},
97-
mounted() {
98-
this.renderChart()
99-
},
100105
methods: {
101-
renderChart() {
106+
renderChart () {
102107
this.destroyChart()
103108
this.chart = new Chart(
104109
this.$refs.canvas.getContext('2d'),
105110
this.chartConfig
106111
)
107112
},
108-
updateChart() {
113+
updateChart () {
109114
Object.assign(this.chart, this.chartConfig)
110115
this.chart.update()
111116
},
112-
destroyChart() {
117+
destroyChart () {
113118
if (this.chart) {
114119
this.chart.destroy()
115120
}
116121
}
117122
},
118-
beforeDestroy() {
119-
this.destroyChart()
120-
},
121123
render(h) {
122124
return h(
123125
'div',

0 commit comments

Comments
 (0)