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

62 lines
1.4 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
2021-11-17 19:20:07 +08:00
*/
export const useChart = (domId: string): Ref<echarts.ECharts> => {
2021-11-16 19:01:03 +08:00
let chartContainer: HTMLCanvasElement;
const selfChart = ref<echarts.ECharts | any>();
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;
2021-11-17 19:20:07 +08:00
};
/**
* counter utils
* @param duration
* @returns
2021-11-17 19:20:07 +08:00
*/
export const useCounter = (duration = 60): [Ref<number>, () => void] => {
let intervalTimer: NodeJS.Timer;
2021-11-17 19:20:07 +08:00
onMounted(() => {
clearInterval(intervalTimer);
});
2021-11-17 19:20:07 +08:00
const countDown = ref(0);
return [
countDown,
() => {
countDown.value = duration;
intervalTimer = setInterval(() => {
if (countDown.value > 0) {
countDown.value -= 1;
} else {
clearInterval(intervalTimer);
countDown.value = 0;
}
}, 1000);
},
];
};