在微信小程序中使用ECharts
1. 下載插件
首先,下載 GitHub 上的 ecomfe/echarts-for-weixin 項目。
下載鏈接:ecomfe/echarts-for-weixin
2. 運行項目可查看圖表示例
3. 使用組件
//ec-canvas
是提供的組件,將文件夾ec-canvas
復制到自己的項目中
//配置要應用組件的json
文件,我這里是home.json,一定注意路徑要寫對。
{
"usingComponents": {
"ec-canvas": "../../ec-canvas/ec-canvas"
}
}
// 在home.js引用echarts
import * as echarts from '../../ec-canvas/echarts';
//配置全局css
/**app.wxss**/
.container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex; /* flex布局 */
/* 注意:設為Flex布局以后,子元素的float、clear和vertical-align屬性將失效。 */
flex-direction: column; /*決定主軸的方向(即項目的排列方向) */
/* column:主軸為垂直方向,起點在上沿。*/
align-items: center; /*定義項目在交叉軸上如何對齊 */
/* center:交叉軸的中點對齊*/
justify-content: space-between; /* 定義了項目在主軸上的對齊方式 */
/* space-between:兩端對齊,項目之間的間隔都相等 */
box-sizing: border-box;
/* content-box:padding和border不被包含在定義的width和height之內 盒子的實際寬度=設置的width+padding+border border-box:padding和border被包含在定義的width和height之內。 盒子的實際寬度=設置的width(padding和border不會影響實際寬度) */
}
//home.wxml
<view class="container">
<ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>
其中 ec 是一個我們在 index.js 中定義的對象,它使得圖表能夠在頁面加載后被初始化並設置。
//home.wxss
ec-canvas {
width: 100%;
height: 50%;
background: #eee;
}
//home.js
Page({
data: {
ec: {
onInit: initChart
}
}
});
function initChart(canvas, width, height) {
const chart = echarts.init(canvas, null, {
width: width,
height: height
});
canvas.setChart(chart);
var option = {
...
};
chart.setOption(option);
return chart;
}
這對於所有 ECharts 圖表都是通用的,用戶只需要修改上面 option 的內容,即可改變圖表。option 的使用方法參見 ECharts 配置項文檔。對於不熟悉 ECharts 的用戶,可以參見5 分鍾上手 ECharts 教程 。