本篇文章基于Vue2进行开发
首先Echarts改变的原理是通过修改option来调整样式以及数据,了解到这一点之后我们就有了一些思路,既然是封装组件,可以选择父子组件传值的方法,将我们需要的样式以及数据传入组件当中,组件接收到数据,根据不同的数据渲染出对应的图表
首先第一步:
<template>
<!-- 定义一个标签用来创建画布 -->
<div id="main" ref="echartpie"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
// 组件传参(父传子)
props: {
opValue:{
type: Object,
},
},
data() {
return {
// 实例图表的变量
myChart: null
}
},
computed: {},
// 监听父组件传递过来的数据
watch: {
opValue: {
handler() {
this.setOption(); // 数据有变化便重新渲染图表
},
deep: true // 深度监听
}
},
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {
// 创建echarts实例
this.myChart = echarts.init(this.$refs.echartpie);
// 渲染图表
this.setOption();
},
methods: {
// 完善一下渲染图表的方法
setOption() {
this.myChart && this.opValue && this.myChart.setOption(this.opValue);
}
},
beforeUpdate() {},
updated() {},
beforeDestroy() {
// 页面销毁前判断图表实例是否存在
this.myChart && this.myChart.dispose();
},
destroyed() {}
}
</script>
<style lang='scss'>
</style>
<style lang='scss' scoped>
#main{
// 图表宽高自适应
width: 100%;
height: 100%;
}
</style>
做完以上的操作,我们的图表就已经初现雏形了
接下来再给图表组件做一个自适应:
<template>
<!-- 定义一个标签用来创建画布 -->
<div id="main" ref="echartpie"></div>
</template>
<script>
import * as echarts from 'echarts';
// 防抖
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
export default {
// 组件传参(父传子)
props: {
opValue:{
type: Object,
},
},
data() {
return {
// 实例图表的变量
myChart: null
}
},
computed: {},
// 监听父组件传递过来的数据
watch: {
opValue: {
handler() {
this.setOption(); // 数据有变化便重新渲染图表
},
deep: true // 深度监听
}
},
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {
// 创建echarts实例
this.myChart = echarts.init(this.$refs.echartpie);
// 渲染图表
this.setOption();
// 添加resize方法(页面大小发生变化时触发)
window.addEventListener('resize', debounce(() => {
this.myChart.resize();
}, 200));
},
methods: {
// 完善一下渲染图表的方法
setOption() {
this.myChart && this.opValue && this.myChart.setOption(this.opValue);
}
},
beforeUpdate() {},
updated() {},
beforeDestroy() {
页面销毁前将resize事件删除
window.removeEventListener('resize', this.handleResize);
// 页面销毁前判断图表实例是否存在
this.myChart && this.myChart.dispose();
},
destroyed() {}
}
</script>
<style lang='scss'>
</style>
<style lang='scss' scoped>
// 图表宽高自适应
#main{
width: 100%;
height: 100%;
}
</style>