Vue+Echarts封装成组件使用及说明
作者:沉默是金~
文章总结了将Vue和Echarts封装成组件的经验,强调了组件的自适应功能,作者希望这个经验对大家有所帮助,并鼓励大家支持脚本之家
Vue+Echarts封装成组件
echarts组件
<template>
<div :id="chartId" :style="style"></div>
</template>
<script>
import * as echarts from "echarts";
//防抖
const debounce = function (fn, delay) {
let timer = null;
return function () {
let content = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(content, args);
}, delay);
};
};
export default {
name: "yw-echarts",
props: {
height: {
type: String,
default: "500px",
},
width: {
type: String,
default: "500px",
},
options: {
type: Object,
default: null,
},
chartId: {
type: [String, Number],
default: null,
},
minHeight: {
type: String,
default: "none",
},
},
data() {
return {
myCharts: null, //echarts实例
};
},
computed: {
style() {
return {
height: this.height,
width: this.width,
minHeight: this.minHeight,
};
},
},
watch: {
options: {
handler(newVal, oldVal) {
if (this.options) {
// this.myCharts.clear();
this.myCharts.setOption(newVal, true);
} else {
this.initChart();
}
},
deep: true,
},
},
created() {
// 防抖优化
this.handleResize = debounce(() => {
this.myCharts.resize();
}, 300);
},
mounted() {
this.initChart();
},
beforeDestroy() {
if (!this.myCharts) return;
// 移除监听
window.removeEventListener("resize", this.handleResize);
// 销毁echarts实例
this.myCharts.clear();
this.myCharts.dispose();
this.myCharts = null;
},
methods: {
initChart() {
this.$nextTick(() => {
if (!this.myCharts) {
this.myCharts = echarts.init(document.getElementById(this.chartId));
}
if (this.options) {
this.myCharts.setOption(this.options, true);
}
if (this.myCharts) window.addEventListener("resize", this.handleResize);
});
},
},
};
</script>
<style lang="scss" scoped></style>
使用
<Echarts
:height="echartsNxObj.height"
:width="echartsNxObj.width"
:options="echartsNxObj.options"
:chartId="echartsNxObj.chartId"
/>总结
支持自适应~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
