echarts+vue,根据窗口变化重新渲染

本文介绍了如何在Vue项目中使用ECharts库,使图表能够根据浏览器窗口尺寸变化自动重绘,确保在不同屏幕尺寸下保持良好的显示效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mounted() {
    this.initView()
    let that = this
    window.addEventListener("resize", () => { 
    that.materialCharts.resize();
    });
 },
  //在initView中
  initView() {
  	....
  	this.materialCharts = this.$echarts.init(document.getElementById('equipClassify'))
      this.materialCharts.setOption(options)
      this.materialCharts.resize()
	}
Vue3中,你可以通过绑定一个计算属性来动态计算echarts盒子的宽高,使其随窗口变化而同比变化。具体实现步骤如下: 1. 在组件的template中,使用ref指令给echarts盒子命名,方便在组件的逻辑代码中获取该元素的实例。 ```html <template> <div class="echarts-container" ref="echartsBox"></div> </template> ``` 2. 在组件的逻辑代码中,使用watch监听窗口大小的变化,并且动态计算echarts盒子的宽高。 ```javascript <script> import * as echarts from 'echarts'; export default { name: 'EchartsBox', data() { return { chartInstance: null // echarts实例对象 } }, computed: { echartsBoxStyle() { const width = this.$refs.echartsBox.clientWidth; const height = width * 0.75; // 宽高比为4:3 return { width: `${width}px`, height: `${height}px` } } }, mounted() { // 初始化echarts this.chartInstance = echarts.init(this.$refs.echartsBox); // ... }, watch: { '$route'(to, from) { // 监听路由变化重新渲染echarts this.chartInstance.resize(); }, // 监听窗口大小变化,动态计算echarts盒子的宽高 '$root.$data.windowSize'(newVal, oldVal) { this.chartInstance.resize(); } }, beforeDestroy() { // 销毁echarts实例对象 this.chartInstance.dispose(); } } </script> ``` 3. 在父组件中,通过监听窗口大小的变化,动态改变根实例中的windowSize属性值。 ```javascript <script> export default { name: 'App', data() { return { windowSize: { width: window.innerWidth, height: window.innerHeight } } }, mounted() { window.addEventListener('resize', this.handleResize); }, destroyed() { window.removeEventListener('resize', this.handleResize); }, methods: { handleResize() { this.windowSize = { width: window.innerWidth, height: window.innerHeight }; } } } </script> ``` 完成以上三个步骤后,echarts盒子就可以随着窗口大小的变化而同比变化了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值