Charts.nvue
1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<template>
<view style="width: 100%;flex: 1;height: 100%;">
<!-- #ifdef MP-WEIXIN -->
<l-echart ref="chartRef" @finished="init" :custom-style="`width:654rpx;height:${height}`"></l-echart>
<!-- #endif -->
<!-- #ifndef MP-WEIXIN -->
<l-echart ref="chartRef" @finished="init"></l-echart>
<!-- #endif -->
</view>
</template>
<script setup>
const props=defineProps({
height:{
type:String,
default:'420rpx'
}
})
import {
ref,
onMounted,
shallowRef
} from 'vue';
import lEchart from '../uni_modules/lime-echart/components/l-echart/l-echart.vue';
// #ifndef MP-WEIXIN
import * as echarts from 'echarts';
// #endif
// #ifdef MP-WEIXIN
const echarts = require('../uni_modules/lime-echart/static/echarts.min');
// #endif
const chartRef = ref(null);
const myChart = shallowRef(null);
// 初始化 Promise 及 resolve 函数
const initializePromise = ref(null);
let resolveInitialize = null;
// 保证函数执行时initCharts一定在init后面
onMounted(() => {
initializePromise.value = new Promise((resolve) => {
resolveInitialize = resolve;
});
});
// 默认配置
const defaultOption = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}]
};
const init = async (e) => {
if (!chartRef.value) return;
try {
myChart.value = await chartRef.value.init(echarts);
console.log('图表初始化完成');
// 解决 Promise,通知初始化完成
if (resolveInitialize) {
resolveInitialize();
resolveInitialize = null; // 防止重复调用
}
} catch (error) {
console.error('图表初始化失败:', error);
}
};
/**
* 暴露方法,进行图表渲染
*/
const initCharts = async (options = defaultOption) => {
await initializePromise.value; // 等待初始化完成
myChart.value?.setOption(options);
};
defineExpose({
initCharts
});
</script>