vue.js vue-chartjs 图表在 chartData 替换、更新等时不更新

vue.js vue-chartjs chart not updating when chartData replaced, updated etc

我正在尝试用 vue-chartjs 制作一个 vue。当 chartData 道具更新时,我已经遵循了所有关于重新渲染图表的相关文档。我的图表只会在我调整浏览器大小后更新 window。

我的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 中选择和更改数据集合方面的工作。除非我调整 window 的大小,但图表不会重新呈现。当 parenttestchart.vue 最初加载时,我收到以下错误: 'Uncaught TypeError: Cannot read 属性 'transition' of null' 。但这似乎没有任何影响,因为调整 window 的大小将呈现图表的初始显示。更新数据 changetestthing 方法确实会正确更新数据集合 (chartData),但除非我调整 window 的大小,否则它不会重新呈现。

如何强制图表重新呈现?我如何获得对父级中 TestChart 组件的引用? this.TestChart 未定义。我只是想从参考中获取参考,以防我可以手动调用 'renderChart' 。谢谢。

*** 更新

我能够通过以下修改更新图表:

我从 c​​hangetestthing 方法中删除了以下行:

this.datacollection.datasets = null;
this.datacollection.labels = null;

并将数据收集赋值语句更改为:

this.datacollection = Object.assign({}, this.datacollection, { labels: labels, datasets: datasets });

我不能肯定地说这是最佳做法。根据 vue.js 文档 (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

所以我相信不将 datacollection.labels 和 .datasets 属性设置为 null 然后使用 Object.assign 会触发更改。我仍然不确定为什么没有使用 mixins 或手动手表触发它们。任何评论表示赞赏。

一种可行的方法是在图表中添加观察者,

props: ['chartData', 'options'],
mounted () {
  this.renderChart(this.chartData, this.options)
},
watch: {
  'chartData' (to, from) {
    this.renderChart(this.chartData, this.options)
  }
},

参见示例 CodePen


编辑 - 观察者不工作

您的代码和工作的 CodePen 之间的区别在于 CodePen 会改变传递到图表中的变量,因此它是 watcher 的反应。
您的代码改变了变量的 .datasets 属性 - 此引用存在一个已知问题:Mixins don't seem to trigger a refresh of the chart #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})
   }
})

这在我的 view.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 并在我的 view.vue 中生成 因此:

   <pie-chart-city :chartData="CityDatac" :width="300" :height="250"></pie-chart-city>

希望对 VUE.js -> Vue-chartjs.js

中的任何人有所帮助

Alexis Poo 发布的代码为我指明了正确的方向。

在我的例子中,我需要稍微修改一下 watch 对象。

试图通过调用this._chart.destroy()选项更改时销毁图表时,我收到了一个错误消息:cannot read property 'destroy' of undefined

要解决这个问题,我必须改为 this.$data._chart.destroy()

希望对您有所帮助。