• 如何解决A组件通过 props 向子组件B传递数据无法刷新Echart数据的问题?
  • 发布于 2个月前
  • 135 热度
    0 评论
场景描述:在父组件中A.vue引入了子组件B.vue,B.vue实现了对Echart的简单封装,A组件通过 props 向子组件B中传递数据,现在想让A组件中图表数据的变化同步到子组件B中,最初写法:
A.vue
<template>
  <div class="echart-wapper">
        // 堆代码 duidaima.com
        // B组件即 BarChart
        <BarChart ref="chart" :option="option"></BarChart>
  </div>
</template>
<script>
export default {
    data() {
      return {
        option: {}
      }
    },
    created() {
      this.option = [
            { month: '1', count: Math.ceil(Math.random() * 100 + 1) },
            { month: '2', count: Math.ceil(Math.random() * 100 + 1) },
            { month: '3', count: Math.ceil(Math.random() * 100 + 1) },
            { month: '4', count: Math.ceil(Math.random() * 100 + 1) },
            { month: '5', count: Math.ceil(Math.random() * 100 + 1) },
            { month: '6', count: Math.ceil(Math.random() * 100 + 1) }
          ]
      this.$refs.chart.refreshChart()
    }
}
</script>
B.vue
<template>
  <div id="barchart-container">
    <div id="BarChart" ref="BarChart"></div>
  </div>
</template>
<script>
export default {
  name: 'BarChart',
  props: {
    // 图表配置
    option: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      // 当前图表
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$refs.BarChart)
      this.chart.setOption(this.option)
    },
    refreshChart() {
      this.chart.setOption(this.option)
    }
  }
}
</script>
<style>
</style>
出现的问题:子组件B中的图表并无变化,并且当通过下列列表放入不同数据时,点击不同的列表项图表展示的数据会错乱
最后解决通过在子组件 refreshChart 方法中使用 vue 的 $nextTick 方法解决问题:
B.vue
<template>
  <div id="barchart-container">
    <div id="BarChart" ref="BarChart"></div>
  </div>
</template>
<script>
export default {
  name: 'BarChart',
  props: {
    // 图表配置
    option: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      // 当前图表
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$refs.BarChart)
      this.chart.setOption(this.option)
    },
    refreshChart() {
      // 要在数据改变并且 DOM 重新渲染之后再重新设置图表配置,否则不会生效
      this.$nextTick(() => {
        this.chart.setOption(this.option)
      })
    }
  }
}
</script>
<style>
</style>
为什么要这么写呢,因为父组件A中的option是通过props传递给了B组件的option,此时A组件的option就已经绑定上B组件props中的option对象了,当A组件中更新了option的数据,那么B组件中option也会发生改变,因为监听到数据变化,此时B组件的图表DOM就会开始更新,使用 $nextTick 方法就是在DOM元素更新完毕之后再执行其中的方法,即图表重新渲染完毕之后再将option中的更新数据填充上去,此时图表的数据就发生了更新,而之前没有使用$nextTick,在图表DOM还没有更新完毕(即图表还没有渲染出来),就将option设置给图表,当图表渲染出来,图表中的option还是之前的option,所以才没有发生改变。
用户评论