vue+echart+自定义指令:自适应图表
vue+echart+自定义指令:自适应图表,图表根据宽高拉伸变化而重置变化。
之前有用到过其它方式实现,现在只用指令来实现:
<template> <div class="box"> <div ref="zhex" v-resize="resize" style="width:40%;height:100%;bakcground:pink;"> </div> </div> </template> <script> import * as echarts from 'echarts' export default { name: '', data() { return { opt:null } }, mounted() { this.zhexchartInit() }, directives:{ resize:{ bind(el,binding){ let width="" let height="" function isResezi(){ const style = document.defaultView.getComputedStyle(el); if(width!==style.width||height!==style.height){ binding.value() // 关键 } width = style.width height = style.height } el.__vueSetInterval__ = setInterval(isResezi,300) }, unbind(el){ clearInterval(el.__vueSetInterval__) } } }, methods: { resize(){ console.log('changed---') this.myChart.clear() this.myChart.setOption(this.opt) }, // 折线图表 zhexchartInit() { this.myChart = echarts.init(this.$refs.zhex) this.opt = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [120, 200, 150, 80, 70, 110, 130], type: 'bar', showBackground: true, backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)' } } ] } this.myChart.setOption(this.opt) } }, components: {} } </script> <style scoped lang="less"> .box{ width:100%; height:100vh; background:peachpuff; p{font-size:30px;} } </style>
这个图表就会根据div的改变而重载,这里涉及两个知识点,一个是指令相关,一个是重绘图表