在使用之前 ,還是請詳細閱讀官網文檔
官方文檔還是講的比較詳細,在json、wxml中引入,基本上就完成了前期配置,下面就是在js中,如何創建自定義設置並動態渲染echart圖表了
在js中 引入
import * as echarts from '../../ec-canvas/echarts';設定
設定4個全局變量(根據使用情況自行定義,我這就隨便定義了)
let chart; let time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, , 23, 24, 25, 26, 27, 28, 29, 30]; let views = []; let buyNum = [];
接下來就是創建圖表數據方法(我這是使用折線圖)注 :我的是放在page外面的,也可根據自己喜好
function onInit(canvas, width, height) { chart = echarts.init(canvas, null, { width: width, height: height }); canvas.setChart(chart); chart.showLoading();//這里是緩沖動畫 var option = { tooltip: { trigger: 'none'//這里是圖表中點擊指示點后的提示框,現在我已禁止,開啟為axis字段 }, color: ['#00A1D6', '#F5C500'],//這是自定義副標顏色 legend: { left:"left",//這是副標位置,更多查看官網 data: ['瀏覽量', '購買量']//這是副標 }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true//這里設置圖表距容器距離,也可設定為具體值,boolean狀態為當數據過多時是否溢出容器 }, xAxis: { type: 'category', boundaryGap: false, axisLabel: { interval: 2,//設定刻度距離,距離2顯示一個刻度 textStyle: { fontsize: '10rpx',設置字體大小,顏色等 } }, data: time },//這里為x坐標 yAxis: { min: 0,//y坐標最小值 max: 500,//y坐標最大值,也可不設值,它會根據數值大小自行判定 type: "value" },//這里為y坐標 series: [{ name: '瀏覽量',//這里為副標所對應的折線 type: 'line', stack: '總量',
symbol:'none',//是否取消指示點
smooth:true,//是否平滑顯示 data: views,//這為動態賦值,下面為附上怎么傳 itemStyle: {//這是自定義樣式,想更多樣式參考官網API normal: { lineStyle: { color: '#00A1D6'//這里為自定義折線顏色 } } }, }, { name: '購買量', type: 'line', stack: '總量', data: buyNum, itemStyle: { normal: { lineStyle: { color: '#F5C500' } } }, } ] }; chart.setOption(option); chart.hideLoading();//這是消除加載動畫 return chart; }
好了 現在我們基本上配置好了
現在就在page中引入了
data: { ecLine: { onInit: onInit }, }
下面是動態渲染數據(放在請求下面,根據實際情況)
agencyIndex().then(res => {
1.取出自己需要的數據
2.賦值給全局變量 time、views 、buyNum
3.動態賦值(我這直接粘貼了,也可直接在這設置樣式,上面主要作用為初始化圖表)
chart.setOption({ series: [{ name: '瀏覽量', type: 'line', stack: '總量', symbol: 'none', smooth: true, data: views, itemStyle: { normal: { lineStyle: { color: '#00A1D6' } } }, }, { name: '購買量', type: 'line', stack: '總量', symbol: 'none', smooth: true, data: buyNum, itemStyle: { normal: { lineStyle: { color: '#F5C500' } } }, } ] });
})
完結過后,發現一個大大的驚喜,兩條數據折線,數據不一樣,但是線條卻重合了(反正我的是這種情況)
解決辦法:在series中stack字段要設為不一樣的,比如我的代碼
chart.setOption({ series: [{ name: '瀏覽量', type: 'line', stack: '瀏覽總量', symbol: 'none', smooth: true, data: views, itemStyle: { normal: { lineStyle: { color: '#00A1D6' } } }, }, { name: '購買量', type: 'line', stack: '購買總量', symbol: 'none', smooth: true, data: buyNum, itemStyle: { normal: { lineStyle: { color: '#F5C500' } } }, } ] });
這樣解決啦!