๐Ÿ“Š Vue.js์—์„œ Chart.js ์‚ฌ์šฉํ•˜๊ธฐ

Cherryยท2023๋…„ 2์›” 3์ผ
0
post-thumbnail

Chart.js๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ˆœ์„œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค

1. chart.js ์„ค์น˜

2. chart.js import

3. canvas ํƒœ๊ทธ

4. ๋ฐ์ดํ„ฐ์™€ ํ•จ์ˆ˜


๐Ÿ‘ฉโ€๐Ÿ’ป chart.js ์„ค์น˜

npm i chart.js

๐Ÿ‘ฉโ€๐Ÿ’ป chart.js import

์‚ฌ์šฉํ•˜๊ณ ์ž ํ•˜๋Š” vue ํŒŒ์ผ์— ์ฐจํŠธ๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ๋„๋ก chart.js๋ฅผ importํ•ด์ค€๋‹ค.

<template>
  <div></div>
</template>

<script>
import { Chart, registerables } from 'chart.js'
Chart.register(...registerables)
</script>

<style>

</style>

registerables๋Š” ๋ชจ๋“  ์ฐจํŠธ๋ฅผ ๊ฐ„ํŽธํ•˜๊ฒŒ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ๋„๋ก ํ•จ

๐Ÿ‘ฉโ€๐Ÿ’ป canvas ํƒœ๊ทธ

js๋ฅผ ์ด์šฉํ•˜์—ฌ ์ฝ˜ํ…์ธ ๋ฅผ ๊ทธ๋ฆด๋•Œ ์‚ฌ์šฉํ•˜๋Š” canvas ํƒœ๊ทธ๋ฅผ ๋„ฃ์–ด ์ฐจํŠธ๊ฐ€ ๋‚˜ํƒ€๋‚  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค.
html์—์„œ๋Š” canvasํƒœ๊ทธ์— id๋‚˜ class์ด๋ฆ„์„ ๋„ฃ์–ด์„œ ์‚ฌ์šฉํ•˜์ง€๋งŒ vue์—์„œ๋Š” refs๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

<template>
  <div>
  <canvas
      ref="MyChart"/>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js'
Chart.register(...registerables)
</script>

<style>

</style>

๐Ÿ‘ฉโ€๐Ÿ’ป ๋ฐ์ดํ„ฐ์™€ ํ•จ์ˆ˜

๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•ด์„œ export default๊ตฌ๋ฌธ์„ ๋„ฃ์–ด์ค€๋‹ค.
importํ•œ Chart๊ฐ€ new Chart()๋กœ ๋งŒ๋“ค์–ด์ง„๋‹ค.
ํ•จ์ˆ˜๋ฅผ ๋ฐ”๋กœ ์‹คํ–‰์‹œํ‚ค๊ธฐ ์œ„ํ•ด์„œ mounted์— ๋งŒ๋“  ํ•จ์ˆ˜๋ฅผ ๋„ฃ์–ด์ค€๋‹ค.

<template>
  <div>
    <canvas
      ref="MyChart"/>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js'
Chart.register(...registerables)

export default {
  data:() => ({
    type: 'bar',
    data: {
      labels: [ 'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange' ],
      datasets: [{
        label: '# of Votes',
        data: [ 12, 19, 3, 5, 2, 3 ],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  }),
  mounted(){
    this.createChart()
  },
  methods:{
    createChart(){
      new Chart(this.$refs.MyChart, {
        type:'bar',
        data:this.data,
        options:this.options
      })

    }
  }

}
</script>

<style>

</style>




๊ทธ๋Ÿฌ๋ฉด ์ด๋ ‡๊ฒŒ ์ฐจํŠธ๊ฐ€ ๊ทธ๋ ค์ง„ ๊ฒƒ์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ๋‹น!
์‹ค์ œ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐจํŠธ์— ๋ฟŒ๋ฆฌ๋Š”๊ฒƒ์€ ๋‹ค์Œ ํฌ์ŠคํŒ…์—์„œ ์•Œ์•„๋ณด๊ฒ ๋‹ค ๐Ÿ”ฅ

profile
๐Ÿ’์˜ ๊ณต๋ถ€๊ณต๊ฐ„

0๊ฐœ์˜ ๋Œ“๊ธ€