基於Ionic3實現選項卡切換並重新載入echarts
阿新 • • 發佈:2020-09-25
要求
選項卡每切換一次,就載入對應的一個echarts 圖,要有一開始的動畫效果
效果如下:
注意點
1、echarts要想每次都能重新載入,需要移除"_echarts_instance_"屬性,否則一切換選項卡,就再也載入不出來了
2、在ts 中獲取html 頁面元素,不能寫在構造方法裡,應該寫在ionViewDidEnter()方法裡
3、選項卡<ion-segment> 不要搭配[ngSwitch] 的方式,因為這種情況下,只能獲取當前選項卡中的元素,未選中的選項卡里的元素獲取不到,在第2步驟ionViewDidEnter() 方法裡自然也是獲取不到。應當搭配(ionChange)使用方式
4、不能直接將chart作為全域性變數,這樣的話第二次載入就沒有動畫效果了
獻上程式碼
html檔案
<ion-header> <ion-navbar> <ion-title>區域</ion-title> </ion-navbar> </ion-header> <ion-content padding> <ion-segment [(ngModel)]="choice" (ionChange)="segmentChanged($event)"> <ion-segment-button value="choice1"> 省份增速排名 </ion-segment-button> <ion-segment-button value="choice2"> 市州增速排名 </ion-segment-button> <ion-segment-button value="choice3"> 全省走勢 </ion-segment-button> <ion-segment-button value="choice4"> 市州佔比 </ion-segment-button> </ion-segment> <div id="chartContainer" style="width: 100%; height: 300px;"></div> </ion-content>
ts檔案
import {Component} from '@angular/core'; import * as echarts from 'echarts'; @Component({ selector: 'page-data-area',templateUrl: 'area.html' }) export class DataAreaPage { choice: string = "choice1"; ec: any = echarts; chartContainer: any; constructor() { } clickChart1() { const chart1 = this.ec.init(this.chartContainer); chart1.setOption({ series: { type: 'pie',data: [{ name: 'A',value: 10 },{ name: 'B',value: 20 },{ name: 'C',value: 30 },{ name: 'D',value: 40 }] } },true); this.chartContainer.removeAttribute("_echarts_instance_"); } clickChart2() { const chart2 = this.ec.init(this.chartContainer); chart2.setOption({ series: { type: 'pie',value: 30 }] } },true); this.chartContainer.removeAttribute("_echarts_instance_"); } clickChart3() { const chart3 = this.ec.init(this.chartContainer); chart3.setOption({ series: { type: 'pie',value: 40 },{ name: 'E',value: 50 }] } },true); this.chartContainer.removeAttribute("_echarts_instance_"); } clickChart4() { const chart4 = this.ec.init(this.chartContainer); chart4.setOption({ series: { type: 'pie',value: 50 },{ name: 'F',value: 60 }] } },true); this.chartContainer.removeAttribute("_echarts_instance_"); } segmentChanged(e) { if (e.value == "choice1") { this.clickChart1(); } else if (e.value == "choice2") { this.clickChart2(); } else if (e.value == "choice3") { this.clickChart3(); } else if (e.value == "choice4") { this.clickChart4(); } } ionViewDidEnter() { this.chartContainer = document.getElementById('chartContainer'); this.clickChart1(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。