代码如下
onMounted(() => { init() }) //初始化数据 const data = ref([]) const init = () => { axios.get('https://c4156a34-94b2-4302-969f-e96f6277625a.bspapp.com/pie').then(res => { data.value = res.data }) // 1通过dom初始化echarts 2ref虚拟化dom let mychart = echarts.init(main.value) // 数据源 var option = { title: { text: '库存剩余', x: 'center' }, tooltip: { trigger: 'item' }, legend: { top: '5%', left: 'center' }, series: [ { name: '库存', type: 'pie', radius: ['40%', '70%'], itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: '40', fontWeight: 'bold' } }, data: data.value } ] }; // 数据源给予 mychart.setOption(option) }
复制
echarts画图,DOM渲染的时候,echarts实现先从后端获取数据再渲染 ,但是执行顺序是先执行
// 数据源给予 mychart.setOption(option)
复制
再执行
axios.get('https://c4156a34-94b2-4302-969f-e96f6277625a.bspapp.com/pie').then(res => { data.value = res.data })
复制
也就是数据都没
而渲染需要的事数据先有再执行,所以得用同步的方法执行,用async await
const init = async () => { await axios.get('https://c4156a34-94b2-4302-969f-e96f6277625a.bspapp.com/pie').then(res => { data.value = res.data }) // 1通过dom初始化echarts 2ref虚拟化dom let mychart = echarts.init(main.value) // 数据源 var option = { title: { text: '库存剩余', x: 'center' }, tooltip: { trigger: 'item' }, legend: { top: '5%', left: 'center' }, series: [ { name: '库存', type: 'pie', radius: ['40%', '70%'], itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: '40', fontWeight: 'bold' } }, data: data.value, } ] }; // 数据源给予 mychart.setOption(option) }
复制