Nuxt에서 Chart.js 사용

소개



Chart.js은 자바 스크립트로 쉽게 아름다운 그래프를 그릴 수있는 차트 라이브러리입니다.

그 Chart.js를 Vue.js에서 이용할 수 있도록 했다.

vue-chart.js 설치



vue-chart.js 을 참고하여 Nuxt 프로젝트에 vue-chart.js 를 설치합니다.
npm install vue-chartjs chart.js --save

chart의 구현 방법



설치가 끝나면 즉시 vue-chart.js를 사용하여 차트를 만들 수 있습니다.
공식 문서 에 의하면 다음의 구현으로 차트를 작성할 수 있습니다.

import { Bar } from 'vue-chartjs'

export default {
  extends: Bar,
  mounted () {
    this.renderChart(data, options)
  }
}

기본적으로는 Nuxt 에서 이용하고 싶은 Chart를 임포트 해, extend한 다음 mounted의 타이밍에 파라미터(데이터 세트, 옵션) 건네 Chart를 렌더링 합니다.

각 page 파일로 위의 구현을 해주면 Chart를 그릴 수 있습니다만, 막대 그래프나 선 그래프, 원 그래프 등 각 Chart마다 Component에 잘라 구현해 주는 것이 좋을 것 같습니다.

그래서 Plugin을 구현하고, 이용하고 싶은 Chart를 Global인 컴퍼넌트로 등록하기로 했습니다.

Plugin 구현



Plugin을 구현할 때 plugins 디렉토리 아래에 vue-chart.js 파일을 만듭니다.
그 안에 프로젝트 내에서 이용하는 chart 컴퍼넌트를 작성해, vue-chartjs 메소드로 Global인 컴퍼넌트로서 등록을 합니다.

이번에는 샘플로 Doughnut Chart 구성 요소 ( vue-chartjs.js )를 만들었습니다.

plugins/vue-chartjs.js

import Vue from 'vue';
import { Doughnut, mixins } from 'vue-chartjs';
const { reactiveProp } = mixins;

Vue.component('doughnut-chart', {
  extends: Doughnut,
  mixins: [reactiveProp],
  props: {
    options: {
      type: Object,
      default: () => {},
    },
  },
  mounted() {
    this.renderChart(this.chartData, this.options);
  },
});

여기서 주의점입니다만, Chart.js 자신은 데이터 세트(this.chartData의 값)가 변경되었을 때, 라이프 업데이트의 기능을 제공하고 있지 않습니다.
실시간 업데이트를 얻으려면 vue-chart.js에서 제공하는 mixin을 사용합니다.
공식 문서
Vue.component 컴퍼넌트에서는 doughnut-chart 를 이용해, props로서 건네받은 데이터 세트가 변경되었을 때에 차트도 라이브 갱신되도록(듯이) 구현했습니다.

Plugin의 구현이 완료되면 doughnut-chartreactiveProp 에 추기를 합니다.

nuxt.config.js

module.exports = {
  // ・・・省略
  plugins: [
    {
      src: '@/plugins/vue-chartjs',
      ssr: false,
    },
  ],
  // ・・・省略
};

chart 구현



Plugin을 작성해, Global인 컴퍼넌트로서 nuxt.config.js 컴퍼넌트를 등록하면, 나머지는 각 Page로부터 그 컴퍼넌트를 호출 차트를 paint 하면 됩니다.

이번에는, 차트의 묘화에 가세해 랜덤하게 데이터를 갱신하는 버튼의 구현도 실시했습니다.

※아래의 샘플은 컴퍼넌트 프레임워크에 h tps : // ゔ 에 쨩 rtjs. 오 rg / gue / # U pdachin g-cha rts 를 이용하고 있습니다.

pages/index.vue

<template>
  <v-container fluid>
    <doughnut-chart :chart-data="chartData" :options="chartOptions"/>

    <div class="text-xs-center mt-2">
      <v-btn dark color="indigo" @click="randomizeData()">Randomize data</v-btn>
    </div>
  </v-container>
</template>

<script>
import colors from 'vuetify/es5/util/colors';

export default {
  data() {
    return {
      chartDataValues: [],
      chartColors: [
        colors.red.lighten1,
        colors.blue.lighten1,
        colors.yellow.lighten1,
        colors.green.lighten1,
      ],
      chartLabels: ['red', 'blue', 'yellow', 'green'],
      chartOptions: {
        maintainAspectRatio: false,
        animation: {
          duration: 1500,
          easing: 'easeInOutCubic',
        },
      },
    };
  },
  computed: {
    chartData() {
      return {
        datasets: [
          {
            data: this.chartDataValues,
            backgroundColor: this.chartColors,
          },
        ],
        labels: this.chartLabels,
      };
    },
  },
  mounted: function() {
    this.randomizeData();
  },
  methods: {
    randomizeData: function() {
      var data = [];
      for (var i = 0; i < this.chartLabels.length; i++) {
        data.push(Math.floor(Math.random() * 100));
      }
      this.chartDataValues = data;
    },
  },
};
</script>

실행 결과는 다음과 같이 되어, 버튼 누름으로 차트가 갱신되는 것도 확인할 수 있었습니다.

Vuetify

좋은 웹페이지 즐겨찾기