I made a small app to confirm how to use chart.js in Nuxt.js. My recent project's language is TypeScript, so I tried to make my code in Typescript. and I also have used Nuxt.js as framework. I referred to this site. But my sample code has error occurred.
first of all, I made chart file as .vue file. my chart components made components directory in Nuxt.js. but in this code, error occurred on @Prop. error message and code is below.
"Property 'chartData' has no initializer and is not definitely assigned in the constructor."
<script lang="ts">
import { Component, Vue, Prop, Watch, mixins } from "nuxt-property-decorator";
import Chart from "chart.js";
import VueChart from "vue-chartjs";
const Line = VueChart.Line;
const reactiveProp = VueChart.mixins.reactiveProp;
@Component
export default class ChartLine extends mixins(Line, reactiveProp) {
@Prop({ default: {} }) chartData: Chart.ChartData;
@Prop({ default: {} }) options: Chart.ChartOptions;
mounted() {
this.renderChart(this.chartData, this.options);
}
}
</script>
In pages of Nuxt.js, I made chart.js file as display chart. so, my code is below
<template>
<div class="chart-container">
<ChartLine
:chartData="chartData"
:options="chartOption"
:styles="chartStyles"
/>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'nuxt-property-decorator'
import { ChartData, ChartOptions } from 'chart.js'
import ChartLine from '~/components/ChartLine.vue'
@Component({ components: { ChartLine } })
export default class ChartPage extends Vue {
private chartData: ChartData = {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [
{
label: 'Data One',
data: [1, 5, 3, 4, 3],
},
{
label: 'Data Two',
data: [10, 50, 30, 40, 30],
},
],
}
private chartOption: ChartOptions = {
maintainAspectRatio: false,
}
private chartStyles = {
height: '100%',
width: '100%',
}
}
</script>
<style lang="scss">
.chart-container {
position: relative;
height: 40vh;
width: 80vw;
margin: 0 auto;
}
</style>
I really don't understand how to fix these error. Could anyone advise me?