解决方案:页面重绘后在执行绘图的代码。vue里面可以把绘图代码放到this.$nextTick里面
描述:
- 首先我们想点击页面上的按钮,弹出一个框,占页面width:80%,height:70%,里面的echart图占对话框的100%。至于为什么要用100比,当然是为了适配不同分辨率了。如下图:
代码如下:
<template>
<div class="echartTest">
<Modal
v-model="modal1"
class-name="modal-wrap-cate"
footer-hide
:transfer="false">
<div ref="echart" class="echart-box"></div>
</Modal>
<Button type="primary" @click="drawEchart" >绘图</Button>
</div>
</template>
<script>
const echarts = require("echarts/lib/echarts"); // 引入 ECharts 主模块
require("echarts/lib/component/grid");
require("echarts/lib/chart/line");//引入折线
export default {
data(){
return{
modal1:false
}
},
methods:{
drawEchart(){
this.modal1=true
let myChart=echarts.init(this.$refs.echart)
let option = {
grid:{
left:50,
right:50,
top:50,
bottom:50
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
};
myChart.setOption(option)
}
}
}
</script>
<style lang="less">
.echartTest{
.modal-wrap-cate{
.ivu-modal{
width: 80% !important;
height:70% !important;
.ivu-modal-body {
padding: 54px 92px;
}
}
.ivu-modal-content {
width: 100%;
height: 100%;
.ivu-modal-body{
width: 100%;
height: 100%;
}
}
.echart-box{
width:100%;
height: 100%;
}
}
}
</style>
结果:显然没有我们想要的效果,查看页面元素发现,设置100%的canvas元素居然变成100px,这是因为没有找到元素的大小所以画了个基础约定的大小100px。如下图:
现在我们将绘图的代码放到$nextTick里面,代码如下:
<template>
<div class="echartTest">
<Modal
v-model="modal1"
class-name="modal-wrap-cate"
footer-hide
:transfer="false">
<div ref="echart" class="echart-box"></div>
</Modal>
<Button type="primary" @click="drawEchart" >绘图</Button>
</div>
</template>
<script>
const echarts = require("echarts/lib/echarts"); // 引入 ECharts 主模块
require("echarts/lib/component/grid");
require("echarts/lib/chart/line");//引入折线
export default {
data(){
return{
modal1:false
}
},
methods:{
drawEchart(){
this.modal1=true
this.$nextTick(()=>{
let myChart=echarts.init(this.$refs.echart)
let option = {
grid:{
left:50,
right:50,
top:50,
bottom:50
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
};
myChart.setOption(option)
})
}
}
}
</script>
<style lang="less">
.echartTest{
.modal-wrap-cate{
.ivu-modal{
width: 80% !important;
height:70% !important;
.ivu-modal-body {
padding: 54px 92px;
}
}
.ivu-modal-content {
width: 100%;
height: 100%;
.ivu-modal-body{
width: 100%;
height: 100%;
}
}
.echart-box{
width:100%;
height: 100%;
}
}
}
</style>
当我们点击按钮的时候,会触发按钮的那段代码,页面的对话框还没出来,此时绘图其实已经完成了。所以我们看到的100px其实就是还没显示对话框之前画的图。this.$nextTick就是等页面渲染完再执行,也就是对话框出来后,画echart的元素就有大小了。所以效果就出来了。
————————————————
原文链接:https://blog.csdn.net/weixin_44494811/article/details/107856879