programing

동적 소품 포함 VueJ 및 ChartJ

goodcopy 2022. 7. 3. 23:21
반응형

동적 소품 포함 VueJ 및 ChartJ

vue-chartjs를 사용하여 막대 그래프를 렌더링하고 있습니다.두 가지 문제가 있습니다.

1) 부모 컴포넌트에서 이 자 컴포넌트로 푸시된 소품을 사용하면 아무것도 렌더링되지 않습니다.(아래 코드에서는 test_data를 사용하도록 차트를 설정하면 test_data와 동일한 데이터가 렌더링되지 않습니다.)

2) columnsprop과 dataprop에 대해 아래 오류가 계속 발생 - 보시다시피 계산된 속성을 사용하려고 했지만 도움이 되지 않았습니다.

vue-chartjs.min.js:8 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "columnsprop" 

BarChart.vue

<script>
import { Bar } from 'vue-chartjs'

export default Bar.extend({
  name: 'BarChart',
  props: ['dataprop', 'columnsprop'],
  computed: {
    datavalues: function(){
      return this.dataprop
    },
    columnvalues: function(){
      return this.columnsprop
    }
  },
  data () {
    return {
      options: {
        animation: false,
        responsive: true,
        maintainAspectRatio: false
      },
      test_data: {
        labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        datasets: [
          {
            label: 'Example Data',
            backgroundColor: '#f87979',
            data: [100, 70, 50, 30, 20, 15, 10, 8, 7, 5]
          }
        ]
      },
      chart_data: {
        labels: this.columnvalues,
        datasets: [
          {
            label: 'Actual Data',
            backgroundColor: '#f87979',
            data: this.datavalues
          }
        ]
      }
    }
  },
  mounted () {
    this.renderChart(this.chart_data, this.options)
  },
  watch: {
    dataprop: function () {
      console.log('>>watch dataprop chart_data.datasets.data: ' + this.chart_data.datasets[0].data)
      console.log('>>watch dataprop test_data.datasets.data: ' + this.test_data.datasets[0].data)
      this._chart.destroy()
      this.renderChart(this.chart_data, this.options)
    }
  }
})
</script>

다음과 같이 temp 속성을 사용해 보았습니다.[Vue warn] 해결 방법 vue.js 2에서는 값이 덮어쓰기되므로 프로포트를 직접 뮤트하지 않도록 하십시오.

즉,

data () {
    return {
          datatemp: [],
          columntemp: [],
          ...
    },
}
computed: {
  datavalues () {
    return this.datatemp
  },
  columnvalues () {
    return this.columntemp
  }
},
watch: {
    dataprop: function () {
      this._chart.destroy()
      this.datatemp = this.dataprop
      this.columntemp = this.columnsprop
      this.renderChart(this.chart_data, this.options)
    }
}

하지만 여전히 같은 오류가 발생합니다.

좋은 생각 있어요?

언급URL : https://stackoverflow.com/questions/43930021/vuejs-and-chartjs-with-dynamic-props

반응형