watch在echart图表中不起作用'vue中的数据更新

问题描述 投票:0回答:0

我正在使用 echart 和 vue 2,我做了一个简单的 echart 组件。

<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: true
    },
    autoResize: {
        type: Boolean,
        default: true,
      },        
  },
  watch: {

    chartData: {
         deep: true,
         handler(val) {
          console.log('chartdata handler',val);

          this.setOptions(val.legend, val.data);
         }
    },
    width: {
         deep: true,
         handler(val) {
          console.log(' width',val);
        }
    }
  },  
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose();
    this.chart = null;
    
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');
      this.setOptions(
         ['pepper','rice'],
         [
              { value: 0, name: 'pepper' },
              { value: 0, name: 'rice' },
        ]
      );
    },

    setOptions( lengend, data ) {    
      this.chart.setOption({
          title: {
              left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '5%',
            left: 'center',
            data: lengend,
          },
          series: [
            {
              name: 'Access From',
              type: 'pie',
              radius: ['40%', '70%'],
              itemStyle: {
                borderRadius: [20, 5, 5, 10],
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              data: data
            }
          ]
        });
    }
  }
}
</script>

我在另一个父母身上使用这个组件。

   <PieChart ref="pieChart" :chartData="pieData" :width="'400px'"> </PieChart>

  data () {
    return {
        pieData: {
            name: 'crop distribution',
            data:[
                { value: 115, name: 'pepper' },
                { value: 128, name: 'rice' }
            ],
            legend:['pepper','rice']
        },
     }

但是此代码永远不会将数据 - chartData 传递给 PieChart 以更新图形。我调查了一下,发现

  watch: {
    chartData: { deep: true,
         handler(val) {
          console.log('chartdata handler',val);
          this.setOptions(val.legend, val.data);
         }
    },
  }

这个手表功能没有触发,还没有控制台输出

watch 在其他vue 应用中运行良好,但与echart 集成时,这里无法运行。有什么想法吗?

vue.js echarts
© www.soinside.com 2019 - 2024. All rights reserved.