vue3代码,注释齐全
<template>
<div>
<div class="chart" id="chart"></div>
</div>
</template>
<script>
import { defineComponent, ref, onMounted } from 'vue'
import * as echarts from 'echarts'
export default defineComponent({
name: 'environmentMonitor',
setup () {
let myChart
let progressInterval
const progress = ref(parseInt(getRndInteger(0, 10)))
// 初始化echart图形
const initChart = () => {
myChart = echarts.init(document.getElementById('chart'))
const option = {
title: {
text: '0%',
left: 'center',
top: 'center',
textStyle: {
color: '#254e99',
fontSize: '18px'
}
},
series: [
{
type: 'pie',
radius: ['70%', '80%'],
center: ['50%', '50%'],
color: '#000',
data: [
// itemSyle是单项的背景颜色设置。
{ value: 0, itemStyle: { color: '#254e99', borderRadius: 100 }, emphasis: { scale: false } },
{ value: 100, itemStyle: { color: '#f5f5f5' }, emphasis: { scale: false } }
],
label: {
// 将视觉引导图关闭
show: false
},
// 初始化echarts的动画效果
animationType: 'scale',
animationEasing: 'elasticOut',
animationDelay: function (idx) {
return Math.random() * 200
}
}
]
}
myChart.setOption(option)
window.addEventListener('resize', () => {
myChart.resize()
})
}
// 随机设置进度
const setProgress = () => {
if (progress.value > 95) {
// 进度大于95直接设置为100
progress.value = 100
} else {
// 进度增长为5~15之间
const min = progress.value + 5 > 100 ? progress.value : progress.value + 5
const max = progress.value + 15 > 100 ? 100 : progress.value + 15
progress.value = parseInt(getRndInteger(min, max))
}
// 进度为100后停止定时器
if (progress.value === 100) {
clearInterval(progressInterval)
}
resetChart()
}
// 重置echart图形
const resetChart = () => {
const option = {
title: {
text: `${progress.value}%`
},
series: {
data: [
{ value: progress.value, itemStyle: { color: '#254e99', borderRadius: 100 } },
{ value: 100 - progress.value, itemStyle: { color: '#f5f5f5' } }
]
}
}
myChart.setOption(option, false, false)
}
// 生成min~max之间的随机数
function getRndInteger (max, min) {
return Math.floor(Math.random() * (max - min)) + min
}
onMounted(() => {
initChart()
progressInterval = setInterval(setProgress, 1000)
})
return {}
}
})
</script>
<style lang="scss" scoped>
.chart {
height: 300px;
width: 300px;
}
</style>