今天在項目中使用echarts ,項目中,需要點擊對應的圖片,來對折線圖和柱狀圖的切換
首先,HTML代碼是這樣子的:
<div v-if="showType==1" id="lineChart" style="width: 100%;height:100%;"></div> <div v-if="showType==2" id="columnChart" style="width: 600px;height:400px;"></div>
其次,js代碼:
loadEcharts(type) { var that = this; if (type == 1) { that.showType = 1; // 基於准備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('lineChart'), 'light'); var option = { title: { text: '未來一周氣溫變化', subtext: '純屬虛構' }, tooltip: { trigger: 'axis' }, legend: { data: ['最高氣溫', '最低氣溫'] }, toolbox: { show: true, feature: { dataZoom: { yAxisIndex: 'none' }, dataView: { readOnly: false }, magicType: { type: ['line', 'bar'] }, restore: {}, saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] }, yAxis: { type: 'value', axisLabel: { formatter: '{value} °C' } }, series: [ { name: '最高氣溫', type: 'line', data: [11, 11, 15, 13, 12, 13, 10], markPoint: { data: [ { type: 'max', name: '最大值' }, { type: 'min', name: '最小值' } ] }, markLine: { data: [ { type: 'average', name: '平均值' } ] } }, { name: '最低氣溫', type: 'line', data: [1, -2, 2, 5, 3, 2, 0], markPoint: { data: [ { name: '周最低', value: -2, xAxis: 1, yAxis: -1.5 } ] }, markLine: { data: [ { type: 'average', name: '平均值' }, [{ symbol: 'none', x: '90%', yAxis: 'max' }, { symbol: 'circle', label: { position: 'start', formatter: '最大值' }, type: 'max', name: '最高點' }] ] } } ] }; // 使用剛指定的配置項和數據顯示圖表。 myChart.setOption(option); } else { that.showType = 2; // 基於准備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('columnChart'), 'light'); // 指定圖表的配置項和數據 var option = { title: { text: '世界人口總量', subtext: '數據來自網絡' }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'value', boundaryGap: [0, 0.01] }, yAxis: { type: 'category', data: ['巴西', '印尼', '美國', '印度', '中國', '世界人口(萬)'] }, series: [ { type: 'bar', data: [18203, 23489, 29034, 104970, 131744, 630230] } ] }; // 使用剛指定的配置項和數據顯示圖表。 myChart.setOption(option); } },
來回切換的時候,總是報錯:"TypeError: Cannot read property 'getAttribute' of undefined"的錯。。
后來百度了一下,說是dom沒有加載完的問題,要放在this.$nextTick改成
mounted() { this.$nextTick(() => { this.drawLine(); }); }
這樣可以了。
后來測試 了下,用vif控制 隱藏與顯示也是報這樣的錯。。vshow不會。
原理還是一樣吧,vif是dom不加載 的。vshow只是把dom display:none,還是加載了