echart圖表在vue中使用時,因為id是唯一值,所以一般去封裝好后在同一時間同一個頁面中同時使用一個組件會出現只渲染一個組件的問題,這個原因就是因為echart讀取id來進行
option初始化時候不能重復使用。
所以解決這個問題就從這里出發:
思路:在復用封裝好的組件時候綁定不同的id即可。
比這里封裝好一個圖表組件:pie.vue
<template> <div class="pie"> <div > <!-- 為 ECharts 准備一個具備大小(寬高)的 DOM --> <div :id="idPie" :style="{'width':this.width,'height':this.height}"></div> </div> </div> </template> <script> import * as echarts from "echarts" export default { name:"Pie", props:{ width : { type:String, default:'12121' }, height : { type:String, default:'12121' }, idPie:{ type:String, default:'12121' } }, data(){ return { } }, created(){ console.log('props---',this.idPie,this.width,this.height) }, methods:{ //初始化數據 initData() { // 基於准備好的dom,初始化echarts實例 console.log(this.idPie) var myChart = echarts.init(document.getElementById(this.idPie)); // 繪制圖表 myChart.setOption({ title : { text: '某站點用戶訪問來源',//主標題 // subtext: '純屬虛構',//副標題 x:'left',//x軸方向對齊方式 }, tooltip : { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { selectedMode: true, width: 100, itemWidth: 18, itemHeight: 9, right: 10, top: 20, itemGap: 8, textStyle: { padding: [0, 0, 0, 4], fontSize: 12, color: "#0FEBFF", }, }, // legend: { // orient: 'vertical', // bottom: 'bottom', // data: ['直接訪問','郵件營銷','聯盟廣告','視頻廣告','搜索引擎'] // }, series : [ { name: '訪問來源', type: 'pie', radius : '40%', center: ['30%', '40%'], data:[ {value:335, name:'直接訪問'}, {value:310, name:'郵件營銷'}, {value:234, name:'聯盟廣告'}, {value:135, name:'視頻廣告'}, {value:1548, name:'搜索引擎'} ], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }); }, }, mounted(){ this.initData(); }, } </script> <style scoped> </style>
在需要復用的vue中這樣使用即可:
<template> <div class="pieSetting"> <el-card style="width:500px;height:360px;margin:8px;"> <pie id-pie="idpie1" :width="width" :height="height"></pie> </el-card> <el-card style="width:500px;height:360px;margin:8px;"> <pie id-pie="idpie2" :width="width" :height="height"></pie> </el-card> <el-card> 2 </el-card> </div> </template> <script> import pie from "../charts/Pie/pie1.vue" export default { name:"PieSetting", components:{ pie }, data(){ return { width:"200px", height:"380px", } }, methods:{ } } </script> <style scoped> </style>