在vue中使用echarts根据父级div大小自动适应大小
时间: 2024-02-26 19:26:46 浏览: 63
可以通过以下几种方法来实现:
1. 使用百分比设置echarts的宽高,例如:
```html
<template>
<div class="chart-container">
<div ref="chart" class="chart"></div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
mounted() {
this.initChart()
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
initChart() {
const chartDom = this.$refs.chart
const myChart = echarts.init(chartDom)
myChart.setOption({...})
this.myChart = myChart
},
handleResize() {
this.myChart.resize()
}
}
}
</script>
<style>
.chart-container {
width: 100%;
height: 100%;
}
.chart {
width: 100%;
height: 100%;
}
</style>
```
2. 监听父级div的大小变化,然后更新echarts的宽高,例如:
```html
<template>
<div class="chart-container" ref="container">
<div ref="chart" class="chart"></div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
data() {
return {
observer: null
}
},
mounted() {
this.initChart()
this.observer = new ResizeObserver(this.handleResize)
this.observer.observe(this.$refs.container)
},
beforeDestroy() {
this.observer.disconnect()
},
methods: {
initChart() {
const chartDom = this.$refs.chart
const myChart = echarts.init(chartDom)
myChart.setOption({...})
this.myChart = myChart
},
handleResize() {
this.myChart.resize()
}
}
}
</script>
<style>
.chart-container {
width: 100%;
height: 100%;
}
.chart {
width: 100%;
height: 100%;
}
</style>
```
这里用到了`ResizeObserver`来监听父级div的大小变化,但需要注意该API目前只有在Chrome和Firefox浏览器中支持。
阅读全文