首页 > 解决方案 > 无法在 Vue 中的 HighCharts 回调中附加到 JS 对象

问题描述

我正在使用 Vue 3.9.3 和highcharts-vue 1.3.5。我试图在加载时将每个高图放入一个对象中,这样我就可以访问我想要的任何图表

myCharts.aChart或者

myCharts.anotherChart,

所以我可以轻松做到myCharts.anotherChart.addData

在实践中,我这样做,

<highcharts :constructor-type="'stockChart'" :options="options" :callback="chartcallback" ></highcharts>

接着

    data(){
      return{     
        charts:{}
      }
    },
  methods:{ 

       chartcallback(hc){
          let obj = {[hc.options.id] : hc};
          this.charts = Object.assign(this.charts, obj); 

          //also tried this 
          const newChart = {id:hc.options.id, chart : hc};
          this.$set(this.charts, newChart.id, newChart);

          //also tried this
           this.charts = Object.assign({}, this.charts, {
             [hc.options.id] : hc
           });

          //also tried this               
          this.charts[hc.options.id]= hc;

          console.log('test ', this.charts);
        } 
  }

然后我会watch我的数据,每次它们发生变化时,我都会将数据添加到每个高图,

    watch: {
      myData: { 
        immediate: true,
        deep: true,             
        handler(){ 
            this.charts.NameChart.series[0].setData(this.myData[0], true);
            this.charts.DrinkChart.series[0].setData(this.myData[1], true);
            //etc....

this.charts.NameChart或者this.charts.DrinkChart应该在 NameChart 中构造chartcallback,DrinkChart 的值hc.options.id hc.options.id总是有一个值,它就在那里,我检查了。

问题是

chartcallback我做的最后console.log('test ', this.charts);,产生的 obj 是

//first time
{NameChart:chart}

//second time
{NameChart:chart}

但应该是

//first time
{NameChart:chart}

//second time
{NameChart:chart,
DrinkChart:chart}

看起来它会覆盖this.charts每次chartcallback调用。正如我所指出的,我尝试了几种方法,但没有任何效果。

我能做些什么 ?

谢谢

标签: jsonhighchartsvuejs2vue-componentvue2-highcharts

解决方案


推荐阅读