79584581

Date: 2025-04-21 12:03:13
Score: 0.5
Natty:
Report link

You started with a Vue 2 Options API component using: vue-chartjs's component, some mixins,and props for chart data. To convert this Vue 2 component into a class-based component using TypeScript, you’ll want to use "vue-class-component" and "vue-property-decorator". These are two decorator-based libraries that enable class-style Vue development. "vue-class-component" allows defining components as ES6 classes. "vue-property-decorator" gives us decorators like @Prop, @Emit, @Watch, etc.

Firstly, you will have to install dependencies if you haven't already. Type this in your terminal:

npm install vue-class-component vue-property-decorator --save

The solution to this is outlined below:

<script lang="ts">
import { Component, Prop, Mixins } from 'vue-property-decorator'
import { Line } from 'vue-chartjs'
import { chartLast30Days, chartStylingMethods } from '#/mixins'
import { myChartOptions } from '#/const/charts'

@Component
export default class MyLineChart extends Mixins(Line, chartLast30Days, chartStylingMethods) {
  @Prop({ type: Array }) chartPointsDownloads!: any[]
  @Prop({ type: Array }) chartPointsPlays!: any[]
  @Prop({ type: Array }) chartPointsSales!: any[]

  mounted() {
    this.renderChart({
      labels: ['Jan', 'Feb', 'Mar'],
      datasets: [
        {
          label: 'Downloads',
          data: this.chartPointsDownloads,
          backgroundColor: '#f87979',
        }
      ]
    }, myChartOptions)
  }
}
</script>

@Component makes the class a Vue component. extends Mixins(...) allows us to inherit from line (from vue-chartjs) and your mixins (chartLast30Days, chartStylingMethods). So instead of "extends: Line" and "mixins: [...]", we do both using Mixins() from "vue-class-component". @Prop are the props passed to the component, just like in your original props: {...} block. mounted() is the lifecycle hook that runs when the component is inserted into the DOM. renderChart() comes from Line, and lets you draw the chart with custom data. You pass in a dataset (from props) and your myChartOptions.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Prop
  • User mentioned (0): @Emit
  • User mentioned (0): @Watch
  • User mentioned (0): @Prop
  • Low reputation (1):
Posted by: sasha schukken