bug记录:接口异步获取更新数据后,echarts视图没有更新,在下次打开页面后才更新视图。
echarts视图更新是 setOption方法,vue3需要我们在onMounted生命周期和更新(watch)时使用。如果没有视图,查看这两步是否有触发。有视图但是没有更新视图,是 watch 里的setOption没有触发。查看 watch 是否监听到所要更新的数据。因为我是只更新一部分数据,所以开启deep深度监听数据变化。
<template>
<div ref="main" :style="{'height':height,'width': width}" />
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
// 按需引入 echarts
import * as echarts from 'echarts';
const main = ref(); // 使用ref创建虚拟DOM引用,使用时用main.value
const props = defineProps<any>();
onMounted(
() => {
init();
},
);
const init = () => {
// 基于准备好的dom,初始化echarts实例
const myChart = echarts.init(main.value);
// 指定图表的配置项和数据
const options:any = props.option;
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(options, true);
};
watch(() => props.option, (newVal, oldVal) => {
init();
}, { deep: true });
</script>
<style scoped>
</style>