前言:
在此前先给大家安利一个本人现在常用的的echarts库,连接ppchart.com/#/
有感兴趣的朋友可以去look look!!!
正经内容:
<div class="charts-container" :id="id"></div>
`
import { defineProps, defineEmits, onMounted, watch, nextTick, defineExpose } from "vue";
import { init, getInstanceByDom as GetInstanceByDom } from "echarts";
const props = defineProps({
options: {
type: Object,
required: true,
default: () => { },
},
id: {
type: String,
required: true,
default: null,
}
})
const emit = defineEmits(['chart-click']);
let chart = null, chartDom = null;
onMounted(() => {
nextTick(() => {
chart = window.document.getElementById(props.id);
initChartDom();
})
})
watch( () => props.options, () => { if (Object.keys(props.options).length > 0) { if (chart) { nextTick(() => { initChartDom(); chartResizeHandler(); }); } } }, { immediate: true, deep: true, } )
function throttle(fn, delay = 200) { let last, derferTimer; return function (args) { let _self = this; let _args = args; let now = Date.now();
if (last && now < last + delay) {
clearTimeout(derferTimer);
derferTimer = setTimeout(() => {
fn.apply(_self, _args);
}, delay)
} else {
last = now;
fn.apply(_self, _args);
}
}
}
let throttleResize = throttle(chartResizeHandler)
function initChartDom() { if (Object.keys(props.options).length > 0) { chartDom = GetInstanceByDom(chart); if (chartDom) { chartDom.setOption(props.options, true); } else { chartDom = init(chart); chartDom.setOption(props.options, true); // chartDom.on("click", (event) => { emit("chart-click", event) }) } window.addEventListener("resize", throttleResize); } }
function setOption(options) { chartDom.setOption(options); }
function chartResizeHandler() { if (chartDom) { chartDom.resize(); } }
defineExpose({ setOption })
` `.charts-container width: 100%; height: 100%; overflow: hidden; display: flex; justify-content: center; align-items: flex-end; }`