<template>
<div ref="chartContainer" :style="chartStyle"></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
const props = defineProps({
options: {
type: Object,
required: true,
default: () => ({
title: {
text: 'ECharts 示例'
},
grid: {
left: 0,
right: 0,
// 如果需要去除上下padding,可以设置top和bottom
// top: 0,
// bottom: 0,
containLabel: true // 确保标签也在grid区域内
},
tooltip: {},
xAxis: {
type: 'category',
nameLocation: 'center',
axisTick: {
show: false,
alignWithLabel: true
},
data: ['1', '2', '3', '4', '5', '6']
},
yAxis: {},
series: [
{
name: '销量',
type: 'line',
data: [5, 20, 36, 10, 10, 20]
}
]
})
},
style: {
default: () => ({
width: '100%',
height: '100%'
})
}
})
const chartContainer = ref(null)
let chartInstance = null
// 初始化图表
const initChart = () => {
const container = chartContainer.value
if (container) {
chartInstance = echarts.init(container)
chartInstance.setOption(props.options)
// 监听窗口大小变化
window.addEventListener('resize', resizeChart)
}
}
// 调整图表大小
const resizeChart = () => {
if (chartInstance) {
chartInstance.resize()
}
}
// 销毁图表实例
const destroyChart = () => {
if (chartInstance) {
chartInstance.dispose()
window.removeEventListener('resize', resizeChart)
}
}
onMounted(() => {
initChart()
})
onBeforeUnmount(() => {
destroyChart()
})
// 暴露给模板的响应式数据
const chartStyle = props.style
</script>
<style scoped>
/* 样式可以根据需要自定义 */
</style>
vue3 组合式api 封装echarts,并自适应大小
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 前言 接上文,已经安装好了ECharts,开始封装组件方便使用。 一、封装echart图标钩子 首先应用我们之前学...
- Vue3官网[https://v3.cn.vuejs.org/] 1.初识Vue3 (1) 导入vue3 (2) ...
- 一、初始Vue3 Vue3官方地址[https://v3.cn.vuejs.org/] 1、导入Vue3 2、创建...
- Vue.js: 渐进式JavaScript框架官方文档点我直达[https://cn.vuejs.org/] Vu...
- Vue3官网[https://v3.cn.vuejs.org/] 1.初识Vue3 (1) 导入vue3 (2) ...