<template>
<div>
<Button type="primary" @click="viewEchart">模态框中展示echarts</Button>
<Modal v-model="echartModal" width="80%">
<div v-for="i in 3" :key="i">
<div :id="`main${i}`"></div>
</div>
</Modal>
</div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: "echartInModal",
data() {
return {
echartModal:false,
}
},
// echarts初始化一定要在created方法中,因为执行created时没有真实dom节点
mounted() {
},
methods:{
viewEchart() {
this.echartModal = true;
// 必须要使用 $nextTick 因为模态框是异步的
this.$nextTick(()=>{
this.initEchart();
})
},
initEchart() {
let option = {
title: {
text: 'Temperature Change in the Coming Week'
},
tooltip: {
trigger: 'axis'
},
legend: {},
toolbox: {
show: true,
feature: {
dataZoom: {
yAxisIndex: 'none'
},
dataView: { readOnly: false },
magicType: { type: ['line', 'bar'] },
restore: {},
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value',
axisLabel: {
formatter: '{value} °C'
}
},
series: [
{
name: 'Highest',
type: 'line',
data: [10, 11, 13, 11, 12, 12, 9],
markPoint: {
data: [
{ type: 'max', name: 'Max' },
{ type: 'min', name: 'Min' }
]
},
markLine: {
data: [{ type: 'average', name: 'Avg' }]
}
},
{
name: 'Lowest',
type: 'line',
data: [1, -2, 2, 5, 3, 2, 0],
markPoint: {
data: [{ name: '周最低', value: -2, xAxis: 1, yAxis: -1.5 }]
},
markLine: {
data: [
{ type: 'average', name: 'Avg' },
[
{
symbol: 'none',
x: '90%',
yAxis: 'max'
},
{
symbol: 'circle',
label: {
position: 'start',
formatter: 'Max'
},
type: 'max',
name: '最高点'
}
]
]
}
}
]
};
// 假设有多个图表
for (let i = 1;i<=3;i++) {
option && echarts.init(document.getElementById('main' + i)).setOption(option);
}
// var myChart = echarts.init(document.getElementById('main'));
// option && myChart.setOption(option);
},
}
}
</script>
<style scoped>
</style>
总结:在打开Modal时,需要通过$nextTick来包裹初始化echarts的方法