tdesign-vue-next-starter/src/utils/hooks.ts

62 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-11-17 19:20:07 +08:00
import { ref, Ref, onUnmounted, onMounted } from 'vue';
2021-11-16 19:01:03 +08:00
import * as echarts from 'echarts/core';
2021-11-17 19:20:07 +08:00
/**
* eChart hook
* @param domId
* @param chart
*/
export const useChart = (domId: string) => {
2021-11-16 19:01:03 +08:00
let chartContainer: HTMLCanvasElement;
2021-11-17 19:20:07 +08:00
const selfChart = ref<echarts.ECharts>();
2021-11-16 19:01:03 +08:00
const updateContainer = () => {
selfChart.value.resize({
width: chartContainer.clientWidth,
height: chartContainer.clientHeight,
});
};
onMounted(() => {
if (!chartContainer) {
chartContainer = document.getElementById(domId) as HTMLCanvasElement;
}
selfChart.value = echarts.init(chartContainer);
});
window.addEventListener('resize', updateContainer, false);
onUnmounted(() => {
window.removeEventListener('resize', updateContainer);
});
2021-11-17 19:20:07 +08:00
return selfChart
};
/**
* counter utils
* @param duration
* @returns
*/
export const useCounter = (duration: number = 60): [
Ref<number>, () => void
] => {
let intervalTimer = null;
onMounted(() => {
clearInterval(intervalTimer)
})
const countDown = ref(0);
return [countDown, () => {
countDown.value = duration;
intervalTimer = setInterval(() => {
if (countDown.value > 0) {
countDown.value -= 1;
} else {
clearInterval(intervalTimer);
countDown.value = 0;
intervalTimer = null;
}
}, 1000)
}];
}