当图表数据被替换、更新等时,vue.js vue-chartjs 图表不更新

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

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

*** 更新

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

我从 changetestthing 方法中删除了以下行:

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

并将 datacollection 赋值语句更改为:

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

我不能肯定地说这是最佳做法。根据 vue.js 文档 ( https://v2.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 或手动 watch 触发它们。任何评论表示赞赏。

最佳答案

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

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

参见示例 CodePen


编辑 - 观察者不工作

您的代码和工作的 CodePen 之间的区别在于 CodePen 会改变传递到图表中的变量,因此它是观察者使用react。
您的代码改变了变量的 .datasets 属性 - 此引用存在一个已知问题:Mixins don't seem to trigger a refresh of the chart #44 .

尝试替换

this.datacollection.datasets = [];
this.datacollection.labels = [];

用这个(两个地方)

this.datacollection = { datasets: [], labels: [] };

关于当图表数据被替换、更新等时,vue.js vue-chartjs 图表不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148755/

相关文章:

javascript - 当数据集变大时,保持图形中的 Y 轴比例,并在 X 轴上滚动。纵横比问题

vue.js - vuetify 更改选项卡事件

javascript - 使用动态值填充 vue-form-generator 的选择字段

javascript - 同一页面上的相同 Vue 组件两次重复组件 View

javascript - 在 VueJs 中按功能处理按键

javascript - 如何在 Chartjs 2.x 中使用图表插件 (Chart.pluginService.register) 访问标签数组?

chart.js - 获取图表js条形图以填充窗口

jquery - Vue.js 路由和 JQuery - 从路由返回

javascript - Vue.js:如何根据另一个属性更改一组属性

Vue.js 强制计算属性重新计算?