Vue+Echarts封裝成組件使用及說明
更新時間:2025年12月03日 10:31:01 作者:沉默是金~
文章總結了將Vue和Echarts封裝成組件的經(jīng)驗,強調了組件的自適應功能,作者希望這個經(jīng)驗對大家有所幫助,并鼓勵大家支持腳本之家
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() {
// 防抖優(yōu)化
this.handleResize = debounce(() => {
this.myCharts.resize();
}, 300);
},
mounted() {
this.initChart();
},
beforeDestroy() {
if (!this.myCharts) return;
// 移除監(jiān)聽
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"
/>總結
支持自適應~
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue element插件this.$confirm用法及說明(取消也可以發(fā)請求)
這篇文章主要介紹了vue element插件this.$confirm用法及說明(取消也可以發(fā)請求),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

