vue中echarts实现自适应大小

2022年6月11日11:25:26

echarts要实现自适应大小,需要在页面发生大小改变的时候,对图表实例进行重绘。

在echarts里边,提供了一个重绘的方法:resize()图表的实例对象调用该方法即可进行重绘。

然后还需要在vue的钩子函数mounted里边,定义一个window.resize()方法来监听页面发生变化。当页面发生变化时,就执行重绘的方法。

完整示例如下:

<template>
    <div class="echarts">
        <div id="echart"></div>
    </div>
</template>

<script>
import Echarts from 'echarts'
export default {
    data() {
        return{
            myChart: {}
        }
    },
    created() {
        this.$nextTick(()=> {
            this.loadEchart()
        })
    },
    mounted(){
        let _this = this;
        window.onresize = function() {
            _this.myChart.resize()
        }
    },
    methods: {
        loadEchart() {
            this.myChart = Echarts.init(document.getElementById("echart"));
            this.myChart.setOption({
                title: {
                    text: 'ECharts 示例'
                },
                tooltip: {},
                xAxis: {
                    data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
                },
                yAxis: {},
                series: [{
                    name: '销量',
                    type: 'bar',
                    data: [5, 20, 36, 10, 10, 20]
                }]
            })
        }
    }
}
</script>

<style>
#echart {
    width: 50%;
    height: 300px;
}
</style>

效果图:

该示例的数据来自echarts官方,可以根据自己的实际需求来修改数据。原理都是一样的,希望能帮到有需要的人。如果有写的不对的地方也欢迎指出。

  • 作者:苏喂苏喂苏喂su
  • 原文链接:https://blog.csdn.net/joyvonlee/article/details/92016908
    更新时间:2022年6月11日11:25:26 ,共 831 字。