programing

Vue.js 이거 봐.$el.getContext('2d')는 함수가 아닙니다.

coolbiz 2022. 7. 4. 23:06
반응형

Vue.js 이거 봐.$el.getContext('2d')는 함수가 아닙니다.

데이터를 전달할 수 있는 컴포넌트를 작성하기 위해 Vue.js 버전2와 Charts.js를 조작하고 있습니다.이 컴포넌트를 작성하면 이러한 컴포넌트가 보기 좋게 표시됩니다.이것은 나의 코드입니다.

<template>
  <div class="container">
    <canvas width="900" height="400"></canvas>
  </div>
</template>

<script>
    export default {
        props: ['customers','dates'],
        mounted() {
            console.log('Chart-Component mounted.');
            var context = this.$el.getContext('2d');
            console.log(context);
            var myChart = new Chart(context, {
                type: 'line',
                data: {
                    labels: this.dates,
                    datasets: [{
                        label: '# of Votes',
                        data: this.customers,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255,99,132,1)'
                        ],
                        borderWidth: 3,
                        cubicInterpolationMode: 'monotone',
                        lineTension: 0
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }]
                    }
                }
            });

        }
    }
</script>

캔버스에 ID를 지정하고 다음을 통해 컨텍스트를 가져올 경우:

document.querySelector('#graph').getContext('2d');

동작은 괜찮지만 컴포넌트를 한 번만 사용할 수 있습니다.이것은 분명히 제가 원하는 것이 아닙니다.그래서 저는 다음 방법으로 상황을 파악하려고 했습니다.

this.$el.getContext('2d');

다음 오류가 나타납니다.

[Vue warn] :마운트된 후크 오류: "TypeError: this.$el.getContext는 함수가 아닙니다.

구글로 검색해서 의사선생님을 확인했는데, 솔직히 말해서 제가 vue에 처음이라서 더 이상 뭘 검색해야 할지 모르겠어요.

그래서 누군가 나를 도와주거나 내가 다음에 확인해야 할 것을 알려준다면 매우 감사하겠습니다!감사합니다.

this.$el이 경우는 에 대한 언급이다.div#container당신이 원하는 것은 ref를 사용하는 것이다.

ref는 요소 또는 하위 구성요소에 대한 참조를 등록하는 데 사용됩니다.참조는 상위 구성 요소의 $refs 개체 아래에 등록됩니다.

<div class="container">
  <canvas ref="canvas" width="900" height="400"></canvas>
</div>

그리고 나서.

this.$refs.canvas.getContext('2d') 

언급URL : https://stackoverflow.com/questions/44593431/vue-js-this-el-getcontext2d-is-not-a-function

반응형