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代码
<style scoped lang="scss">
.canvas {
height: 100%;
width: 100%;
}
</style>