核心:在dom加载完成后调用echarts实例 的resize()方法
这里是一个例子
这里封装一个echarts
<template>
<div class="container" ref="container"></div>
</template>
<script lang="ts" setup>
import { ref, toRefs, watch, onMounted, nextTick, markRaw, onBeforeMount, inject } from 'vue'
const container = ref<HTMLElement>()
const myChart = ref<any>()
const $echart: any = inject("$echart")
const props = defineProps({
options: {
require: true,
type: Object,
default: {}
}
})
const { options } = toRefs(props)
onBeforeMount(() => {
window.removeEventListener('resize', resizeHandler);
})
onMounted(() => {
myChart.value = markRaw($echart.init(container.value)) //获取echarts实例使用markRaw解除响应式
myChart.value.setOption(options.value)//设置echarts配置项
window.addEventListener('resize', resizeHandler) //监听浏览器窗口大小
})
//核心在这,加载完成后调用该方法,使图表撑满父容器
const resizeHandler = () => {
nextTick(() => {
myChart.value.resize() //设置图表自适应大小
})
}
watch(options, (newOptions) => {
nextTick(() => {
myChart.value.setOption(newOptions) //监听父组件传入的options,发生变化时从新设置配置项
})
},
{ deep: true })
//记得将方法暴漏出去
defineExpose({
resizeHandler
})
</script>
<style scoped>
.container {
width: 100%;
height: 50vh;
}
</style>
在子组件中使用echarts
//在子组件中引入使用echarts
import { ref, nextTick } from 'vue';
<el-dialog v-model="dialogVisible" width="1200" center>
<kdEcharts :options="lineOption" v-if="dialogVisible" ref="kdEchartsR"> </kdEcharts>
</el-dialog>
<script setup>
const dialogVisible = ref(false)
const kdEchartsR = ref()
const open = () => {
dialogVisible.value = true
nextTick(() => {
lineOption.value = {
tooltip: {
trigger: "axis",
axisPointer: {
type: "line"
}
},
xAxis: {
type: 'category', //x轴设置为类目轴
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value', //y轴设置为数值轴
splitLine: {
lineStyle: {
type: 'dashed'
}
}
},
series: [
{
data: [1200, 25565, 224, 218, 135, 147, 260],
type: 'line',//设置图表的类型为折线图,
smooth: true,
symbol: "none",
itemStyle: {
color: "#ff2e4d",
},
emphasis: { disabled: true },
lineStyle: {
color: '#ff2e4d'
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: "#ff2e4d" // 0% 处的颜色
},
{
offset: 1,
color: '#fff' // 100% 处的颜色
}
],
global: false // 缺省为 false
}
}
}
]
}
kdEchartsR.value.resizeHandler()
})
}
defineExpose({
dialogVisible, open
})
</script>
父组件中调用子组件
<templete>
<detail-t ref="detailR"></detail-t>
</templete>
<script setup>
import { reactive, ref } from 'vue';
const detailR = ref()
在需要显示弹框的的方法中调用即可
detailR.value.open()
</script>