Vue+Echarts封装成组件使用及说明
更新时间:2025年12月03日 10:31:01 作者:沉默是金~
文章总结了将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"
/>总结
支持自适应~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue引用BootStrap以及引用bootStrap-vue.js问题
这篇文章主要介绍了vue引用BootStrap以及引用bootStrap-vue.js问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-10-10
把vue-router和express项目部署到服务器的方法
下面小编就为大家分享一篇把vue-router和express项目部署到服务器的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-02-02
基于vue2框架的机器人自动回复mini-project实例代码
本篇文章主要介绍了基于vue2框架的机器人自动回复mini-project实例代码,具有一定的参考价值,有兴趣的可以了解一下2017-06-06
Jenkins+docker容器部署前端Vue项目的完整步骤记录
Jenkins是一个开源软件项目,是基于Java开发的一种持续集成工具,用于监控持续重复的工作,旨在提供一个开放易用的软件平台,使软件项目可以进行持续集成,这篇文章主要介绍了Jenkins+docker容器部署前端Vue项目的完整步骤,需要的朋友可以参考下2026-01-01
关于vue项目一直出现 sockjs-node/info?t=XX的解决办法
sockjs-node 是一个JavaScript库,提供跨浏览器JavaScript的API,创建了一个低延迟、全双工的浏览器和web服务器之间通信通道,这篇文章主要介绍了vue项目一直出现 sockjs-node/info?t=XX的解决办法,需要的朋友可以参考下2023-12-12


最新评论