vue中使用echarts(含自适应监听及移除)

1、html代码

<template>
  <div class="canvas" ref="canvas"></div>
</template>

2、js代码

<script>
export default {
  name: 'BarItemCharts',
  data () {
    return {
      chartIns: '',
      options: {}
    }
  },
  mounted () {
    this.init()
    window.addEventListener('resize', this.onResize)
  },
  methods: {
    init () {
      this.options = {...} // 此处写echarts配置
      if (!this.chartIns) {
        this.chartIns = this.$echarts.init(this.$refs.canvas)
      }
      this.chartIns.setOption(this.options)
    },
    onResize () { 
    // 刚方法是为了确保addEventListener和removeEventListener的东西是同一个
      if (this.chartIns) {
        this.chartIns.resize()
      }
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.onResize)
    if (this.chartIns) {
      this.chartIns.dispose()
    }
  }
}
</script>

上面的onResize 方法也可写在data里,用法一样 写法如下:

data () {
	const onResize = () => {
		if (this.chartIns) {
	      this.chartIns.dispose()
	    }
	}; // 此处声明后记得在return里返回
    return {
   	  onResize, 
      chartIns: '',
      options: {}
    }
  }

3、css代码


你可能感兴趣的:(echarts,vue.js,备忘录,echarts,vue.js,javascript)