Vue에서 DOM을 접근하는 방법인 ref 속성

준영·2023년 11월 11일
0

Vue 이것저것..

목록 보기
6/7
post-thumbnail

Vue에서 DOM을 접근하는 방법인 ref 속성

Chart.js 사용하는 부분에서 자바스크립트 문법으로 직접 DOM에 접근하는 코드를 Vue의 ref 속성을 이용하여 바꿔 보려고 한다.

before code - getElementById 사용 (from JavaScript)

<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>

after code - ref 사용 (from Vue)

<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>
profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글