欢迎来到蕾蕾的博客

echarts数据变了不重新渲染,以及重新渲染了前后数据会重叠渲染的问题

1.echarts数据变了但是视图不重新渲染

新建Chart.vue文件

<template>

 <p :id="id" :style="style"></p>

</template>

<script>

export default {

 name: "Chart",

 data() {

  return {

   //echarts实例

   chart: "" 

  };

 },

 props: {

  //父组件需要传递的参数:id,width,height,option

  id: {

   type: String

  },

  width: {

   type: String,

   default: "100%"

  },

  height: {

   type: String,

   default: "300px"

  },

  option: {

   type: Object,

   //Object类型的prop值一定要用函数return出来,不然会报错。原理和data是一样的,

   //使用闭包保证一个vue实例拥有自己的一份props

   default() {

    return {

     title: {

      text: "vue-Echarts"

     },

     legend: {

      data: ["销量"]

     },

     xAxis: {

      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子","tuoxie"]

     },

     series: [

      {

       name: "销量",

       type: "line",

       data: [5, 20, 36, 10, 10, 70]

      }

     ]

    };

   }

  }

 },

 computed: {

  style() {

   return {

    height: this.height,

    width: this.width

   };

  }

 },

 mounted() {

  this.init();

 },

 methods: {

  init() {

   this.chart = this.$echarts.init(document.getElementById(this.id));

   this.chart.setOption(this.option);

  }

 }

};

</script>

新建App.vue文件,chart在App.vue中简单渲染出来

<template>

 <p id="app">

  <Chart id="test"/>

 </p>

</template>

<script>

import Chart from "./components/Chart";

export default {

 name: "App",

 data() {},

 components: {

  Chart

 }

}

</script>

支持数据自动刷新

//在Chart.vue中加入watch

 watch: {

  //观察option的变化

  option: {

   handler(newVal, oldVal) {

    if (this.chart) {

     if (newVal) {

      this.chart.setOption(newVal);

     } else {

      this.chart.setOption(oldVal);

     }

    } else {

      this.init();

    }

   },

   deep: true //对象内部属性的监听,关键。

  }

 }

2.重新渲染了前后数据会重叠渲染的问题

chart.setOption(option, notMerge, lazyUpdate);将notMerge设置为true就可以echarts画布删除历史数据重新渲染数据

notMerge是可选项,是否不跟之前设置的option进行合并,默认为false,即合并。
posted @ 2019-04-18 16:53  蕾蕾是个程序员  阅读(7496)  评论(0编辑  收藏  举报