在父組件頁面引入兩次該圖表子組件顯示的效果:echarts
因爲是百分比寬高,因此在窗口發生變化時,須要讓圖表也跟着自適應,因此纔出現了本次討論的問題啦。dom
先看下完整的圖表子組件代碼(在父組件就是直接引入,不須要傳參哦):ide
<template> <div ref="pieDom" style="width: 100%;height: 100%;"></div> </template> <script> export default { data () { return { pieEcharts: "", pieOption: {}, datas: [], hideColor: '#6f76ac' } }, mounted() { this.datas = [ { value: 20, name: "25%" }, { value: 80, name: "75%" } ]; this.pieEcharts = this.$echarts.init( this.$refs.pieDom ); this.setPieOption(); this.setPieEvents(); }, methods: { setPieOption(){ this.pieOption = { color: ['#ff106e', this.hideColor], //環形的分段色值設置 tooltip: { trigger: 'item', position: (point, params, dom, rect, size)=> { return [point[0], point[1]]; }, }, series: [{ type: 'pie', radius: ['60%', '80%'], //內存 、外層 avoidLabelOverlap: false, hoverAnimation: true, hoverOffset: 2, label: { normal: { show: false, //中間的標籤 position: 'center', textStyle: { fontSize: '18', fontWeight: 'bold' } }, emphasis: { show: true, textStyle: { fontSize: '20', fontWeight: 'bold' } } }, labelLine: { normal: { show: false } }, selectedOffset: 0, itemStyle: { emphasis: { }, }, data: this.datas }] }; // 渲染圖表 this.pieEcharts.setOption( this.pieOption ); }, /** * 設置圖表的事件 */ setPieEvents(){ /** * 刷新時默認顯示第一條 */ this.pieEcharts.dispatchAction( { type: 'highlight', seriesIndex: 0, dataIndex: 0 } ); /** * 鼠標移入圖表時,不爲第一條時就取消第一條的高亮效果 */ this.pieEcharts.on('mouseover',(v) => { if(v.dataIndex != 0){ this.pieEcharts.dispatchAction({ type: 'downplay', seriesIndex: 0, dataIndex: 0 }); } }); /** * 鼠標圖表時默認顯示第一條 */ this.pieEcharts.on('mouseout',(v) => { this.pieEcharts.dispatchAction( { type: 'highlight', seriesIndex: 0, dataIndex: 0 } ); }); // 監聽窗口變化 - 只刷新最後一個圖表 window.onresize = ()=> { this.pieEcharts.resize(); } // 監聽窗口變化 - 多個圖表同時刷新 window.addEventListener('resize', ()=> { this.pieEcharts.resize(); }) }, } } </script> <style scoped> </style>
窗口改變時圖表自適應代碼在最後,這裏分別提出來作說明:this
1. 只刷新最後一個圖表的狀況:(第二種狀況的代碼記得註釋!)spa
// 監聽窗口變化 - 只刷新最後一個圖表
window.onresize = ()=> {
this.pieEcharts.resize();
}
能夠看到,只有第二個才發生了變化,並且會自動居中和適應大小code
2. 多個圖表同時刷新的狀況:orm
// 監聽窗口變化 - 多個圖表同時刷新
window.addEventListener('resize', ()=> {
this.pieEcharts.resize();
})
兩個同時變化了哦!blog
可是爲何兩個監聽方法會有這樣不一樣的效果呢??? 這個有空的時候再研究。。。知道的朋友能夠留言告訴我哦,萬分感謝seo