创建文件 resize.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useResize(initChartFn) {
const debounce = (func, wait, immediate) => {
let timeout, args, context, timestamp, result;
const later = function () {
const last = +new Date() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function (...args) {
context = this;
timestamp = +new Date();
const callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
}
const clientWidth = ref(
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth
);
const fontSizeRem = (res) => {
if (!clientWidth.value) return;
let fontSize = 100 * (clientWidth.value / 1920);
return res * fontSize;
};
const handleResize = debounce(() => {
clientWidth.value =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
if (typeof initChartFn === 'function') {
initChartFn();
}
}, 500);
onMounted(() => {
window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
window.removeEventListener('resize', handleResize);
});
return {
clientWidth,
fontSizeRem,
updateChart: initChartFn,
};
}
父组件引用 chart1.vue
<template>
<div class="w100 h100" id="container1"></div>
</template>
<script setup>
import { useResize } from "./mixins/resize_test";
import {
ref,
reactive,
toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import Highcharts from "highcharts";
import Highcharts3D from "highcharts/highcharts-3d";
import variablePie from "highcharts/modules/variable-pie";
variablePie(Highcharts);
Highcharts3D(Highcharts);
const props = defineProps({
themeColors: {
type: Array,
default: [
"#2ab6ee",
"#1189ff",
"#bd78fa",
"#f78722",
"#0df7fe",
"#f7c824",
"#6605ff",
"#d67f0b",
],
},
});
const data = reactive({});
let dataCount = ref([]);
let initChart = () => {
Highcharts.setOptions({
colors: props.themeColors,
});
Highcharts.chart(
"container1",
{
tooltip: {
headerFormat: "<span>{point.key}</span><br/>",
pointFormat: "<b>{point.percentage:.1f}%</b>",
style: {
fontSize: fontSizeRem(0.15),
},
},
}
);
};
const { fontSizeRem, updateChart } = useResize(initChart);
const handleChart = (arr) => {
dataCount.value = arr.map((item) => ({
name: item.deviceType,
y: item.deviceCount,
z: item.deviceCount + 16,
}));
setTimeout(() => {
updateChart();
}, 500);
};
defineExpose({
...toRefs(data),
handleChart,
});
</script>
<style scoped lang="scss">
#container1 {
background: linear-gradient(
80.97deg,
rgba(8, 49, 92, 0.5) 0%,
rgba(8, 48, 92, 0) 100%
);
border: 0.00625rem solid rgba(0, 0, 0, 1);
}
</style>