chartData 치환, 갱신 시 vue.js vue-chartjs 차트가 갱신되지 않음
vue-chartjs로 vue를 작성하려고 합니다.chartData prop 업데이트 시 차트 재렌더에 관한 모든 관련 문서를 준수했습니다.내 차트는 브라우저 창의 크기를 조정한 후에만 업데이트됩니다.
parenttestchart.vue 파일:
<template>
<div>
<h1>Chart datacollection update test</h1>
<p>This component demonstrates fetching data from the server.</p>
<p v-if="!datacollection"><em>Loading...</em></p>
<b-form-select
v-model="testthingSelect.selected"
text="Select testthing"
variant="primary"
:options="testthingSelect.options"
:on-change="changetestthing"
class="m-md-2">
</b-form-select>
<test-chart v-cloak :chart-data="datacollection" :chart-option="options"></test-chart>
</div>
</template>
<script>
import TestChart from './TestChart'
export default {
components: {
TestChart
},
data() {
return {
yAxisValues: [],
datacollection: {},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
},
gridLines: {
display: true
}
}],
xAxes: [{
type: "date",
display:true,
gridLines: {
display: false
}
}]
},
legend: {
display: true
},
responsive: true,
maintainAspectRatio: false
},
testthingSelect: {
selected: "EIA/COAL",
disabled: false,
readonly: false,
visible: true,
color: "",
options: [
{
value: null,
text: 'Select a testthing'
},
{
value: "item1",
text: "item1"
},
{
value: "item1",
text: "item1"
},
{
value: "item1",
text: "item1"
}
]
}
}
},
methods: {
changetestthing: async function () {
try {
let response = await this.$http.get(url for my data);
this.datacollection.datasets = [];
this.datacollection.labels = [];
...required data transformations
this.$set(this.datacollection, "labels", labels);
this.$set(this.datacollection, "datasets", datasets);
// this.datacollection.labels = labels;
// this.datacollection.datasets = datasets;
} catch (error) {
console.log(error)
}
}
},
watch: {
'commoditySelect.selected': function () { this.changeCommodity(); }
},
async created() {
// ES2017 async/await syntax via babel-plugin-transform-async-to-generator
// TypeScript can also transpile async/await down to ES5
try {
let response = await this.$http.get(url for my data);
this.datacollection.datasets = [];
this.datacollection.labels = [];
...required data transformations
this.$set(this.datacollection, "labels", labels);
this.$set(this.datacollection, "datasets", datasets);
// this.datacollection.labels = labels;
// this.datacollection.datasets = datasets;
} catch (error) {
console.log(error)
}
} catch (error) {
console.log(error)
}
}
}
TestChart.vue 파일
<script>
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
//Exporting this so it can be used in other components
export default {
extends: Line,
mixins: [reactiveProp],
props: ['chartData', 'options'],
mounted() {
this.renderChart(this.chartData, this.options)
}
}
</script>
이는 상위 vue 내의 데이터 선택을 선택하고 변경하는 데 도움이 됩니다.차트가 다시 렌더링되지 않더라도 창의 크기를 조정하지 않는 한.parent test chart의 경우.vue는 처음에 로드합니다. "Uncatched TypeError: Cannot read property 'transition' of null"이라는 오류가 표시됩니다. 그러나 창의 크기를 조정하면 차트의 초기 표시가 표시되므로 아무 영향도 없는 것으로 보입니다.데이터 변경 방법을 업데이트하면 데이터 선택(chartData)이 올바르게 업데이트되지만 창의 크기를 조정하지 않으면 다시 렌더링되지 않습니다.
차트를 강제로 다시 렌더링하려면 어떻게 해야 합니까?부모의 Test Chart 컴포넌트에 대한 참조를 얻으려면 어떻게 해야 합니까?이.테스트 차트는 정의되어 있지 않습니다.레퍼런스에서 수동으로 '렌더차트'를 호출할 수 있는 경우 레퍼런스를 얻을 수 있는지 궁금할 뿐입니다.감사합니다.
*** 업데이트
아래 수정으로 차트를 갱신할 수 있었습니다.
Changeetesting 메서드에서 다음 행을 삭제했습니다.
this.datacollection.datasets = null;
this.datacollection.labels = null;
또한 데이터 선택 값 할당 문을 다음과 같이 변경했습니다.
this.datacollection = Object.assign({}, this.datacollection, { labels: labels, datasets: datasets });
이것이 베스트 프랙티스라고 단언할 수 없습니다.vue.http://https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats)에 따라 주세요.
new properties added to the object will not trigger changes. In such
cases, create a fresh object with properties from both the original
object and the mixin object
따라서 datacolection.labels 및 .dataset 속성을 null로 설정하지 않고 Object.assign을 사용하면 변경이 트리거된다고 생각합니다.왜 믹스인이나 수동시계를 사용하지 않았는지 아직도 모르겠어요코멘트 감사합니다.
차트에 감시자를 추가하는 것도 한 방법이지만
props: ['chartData', 'options'],
mounted () {
this.renderChart(this.chartData, this.options)
},
watch: {
'chartData' (to, from) {
this.renderChart(this.chartData, this.options)
}
},
CodePen의 예를 참조해 주세요.
편집 - 워처가 작동하지 않음
코드와 동작하고 있는 CodePen의 차이점은 CodePen이 차트에 전달된 변수를 변환하기 때문에 감시자가 반응한다는 것입니다.
의 코드에 " " "가 변환됩니다..datasets
변수의 속성 - 이 참조에는 알려진 문제가 있습니다. 믹스인이 차트 #44를 새로 고치지 않는 것 같습니다.
교환을 시도하다
this.datacollection.datasets = [];
this.datacollection.labels = [];
이것과 함께 (양쪽 모두)
this.datacollection = { datasets: [], labels: [] };
Billy Jean의 마지막 노트는 나에게 PIECHART에 효과가 있었다.JS:
import {
Pie,
mixins
} from 'vue-chartjs'
const {
reactiveProp
} = mixins
export default Pie.extend({
mixins: [reactiveProp],
props: ['options'],
watch: {
'options': {
handler(newOption, oldOption) {
this._chart.destroy()
this.renderChart(this.chartData, this.options)
},
deep: true
}
},
mounted() {
this.renderChart(this.chartData, {responsive: true, maintainAspectRadio:
false})
}
})
제 견해로는 그렇습니다.vue 파일:
let datasets = []
let colorlist = [ '#4e5fa4', '#5e5fa4', '#6e5fa4',
'#7e5fa4', '#8e5fa4', '#a08be4', '#b08bd4']
datasets.push({
label: this.data_by_city_label,
data: this.data_by_city_data,
fill: false,
backgroundColor: colorlist,
pointBorderWidth: 1,
borderWidth: 1,
pointRadius: 0
})
this.CityDatac = Object.assign({}, this.datasets, {labels: this.data_by_city_label, datasets: datasets})
이를 통해 데이터를 PIECHART js로 전송하여 내 뷰에서 생성할 수 있습니다.vue 그대로:
<pie-chart-city :chartData="CityDatac" :width="300" :height="250"></pie-chart-city>
그것이 VUE.js -> Vue-chartjs에 있는 모든 사람에게 도움이 되기를 바랍니다.js
알렉시스 푸가 올린 암호는 내게 올바른 방향을 알려준다.
'를 .watch
조금 반대합니다.
를 호출하여 하려고 할 때this._chart.destroy()
변경되었을 때, 메세지가 되었습니다.cannot read property 'destroy' of undefined
하려면 을 .this.$data._chart.destroy()
★★★★★★ 。
도움이 됐으면 좋겠다.
언급URL : https://stackoverflow.com/questions/47148755/vue-js-vue-chartjs-chart-not-updating-when-chartdata-replaced-updated-etc
'IT이야기' 카테고리의 다른 글
vuex 작업 및 jsdoc: 주입된 함수 매개 변수를 표시하는 방법 (0) | 2022.06.14 |
---|---|
C for-loop의 조건에서는 왜 상수 대신 식을 사용하는가? (0) | 2022.06.14 |
구성 요소를 기존 Vue.js 인스턴스에 등록합니다. (0) | 2022.06.14 |
IntelliJ: 와일드카드 Import 사용 안 함 (0) | 2022.06.14 |
Java에서의 Regex 이름 있는 그룹 (0) | 2022.06.14 |