Chart.js 사용하는 부분에서 자바스크립트 문법으로 직접 DOM에 접근하는 코드를 Vue의 ref 속성을 이용하여 바꿔 보려고 한다.
<template>
<canvas id="myChart02"></canvas>
</template>
<script>
import { Chart } from "chart.js";
export default {
mounted() {
var ctx = document.getElementById("myChart02").getContext("2d");
var chart = new Chart(ctx, {
// The type of chart we want to create
type: "line",
// The data for our dataset
data: {
labels: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45],
},
],
},
// Configuration options go here
options: {},
});
console.log(chart);
},
};
</script>
<template>
<canvas ref="lineChart" id="myChart02"></canvas>
</template>
<script>
import { Chart } from "chart.js";
export default {
mounted() {
// var ctx = document.getElementById("myChart").getContext("2d"); <- before
var ctx = this.$refs.lineChart.getContext("2d");
var chart = new Chart(ctx, {
// The type of chart we want to create
type: "line",
// The data for our dataset
data: {
labels: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45],
},
],
},
// Configuration options go here
options: {},
});
console.log(chart);
},
};
</script>