最后的轉Uni-app項目開發,要用圖表,一個頁面上有好幾個圖表,單個寫的話,代碼量大也麻煩。沒辦法。只能封裝組件了;(本人的項目只用到柱狀圖和餅圖)
組件頁面:
<style lang="scss" scoped> #template { width: 100%; height: 700rpx; .charts { width: 100%; height: 100%; } } </style> <template> <view id="template"><canvas :canvas-id="canvasData.id" :id="canvasData.id" class="charts" @touchstart="touchColumn"></canvas></view> </template> <script> import uCharts from '@/components/u-charts/u-charts.js'; var _self;//只要一個_self; export default { data() { return { cWidth: '', pixelRatio: 1, cHeight: '', }; }, props: ['canvasData'], name: 'mycanvas', methods: { // // 生成圖表 showColumn(chartData) { // 用props回的data添加一個屬性用來生成canvas,以用來控制對應tooltip this.canvasData.canvas = new uCharts({ $this: _self, canvasId: chartData.id, type: chartData.type, fontSize: 12, background: '#FFFFFF', pixelRatio: this.pixelRatio, animation: true, categories: chartData.categories, series: chartData.series, colors: ['#0b974e', '#ffcc00', '#2fce77', '#7030a0', '#ff0000', '#004a96'], xAxis: { disableGrid: true }, yAxis: { min: 0, format: val => { return val.toFixed(0); }, titleFontColor: '#ff0000', title: '日期' }, legend: { show: true, position: 'top', float: 'center', itemGap: 10, padding: 5, lineHeight: 26, margin: 5, borderWidth: 1 }, padding: [5, 35, 5, 5], dataLabel: true, width: _self.cWidth, height: _self.cHeight, extra: { column: { type: 'group', width: (_self.cWidth * _self.pixelRatio * 0.5) / chartData.series.length }, pie: { labelWidth: 15 } } }); }, // // 點擊圖表顯示tooltip touchColumn(e) { if (this.canvasData.type != 'pie') { this.canvasData.canvas.showToolTip(e, { textList: [{ text: '日期:' }, { text: 'OEE:' }], format: function(item, category) { this.textList = [ { text: item.name + ': ' + item.data.value + (item.name == 'OEE' ? '%' : '') }, { text: '日期 : ' + item.data.day } ]; } }); } else { this.canvasData.canvas.showToolTip(e, { textList: [], format: function(item, category) { let p = Math.round(item._proportion_ * 10000) / 100; this.textList = [{ text: item.name + ' : ' + item.data + '分鍾' }, { text: '占比 : ' + p + '%' }]; } }); } } }, mounted() { _self = this; this.cWidth = uni.upx2px(750); this.cHeight = uni.upx2px(600); }, watch: { 'canvasData.day': { // 監聽數據變化后重新生成圖表 handler(newName, oldName) { setTimeout(() => { this.showColumn(this.canvasData); }, 100); }, immediate: true, deep: true } } }; </script>
在頁面引用
template
<u-canvas :canvasData="metreData"></u-canvas>
JS里面
import uCanvas from './canvas'; export default { data() { return { metreData: { type: 'column', categories: [], series: [], id: 'metre', canvas: null, day: 0 }, }; }, components: { uCanvas }, methods: { }, onLoad(item) { } }; </script>
這樣把獲取到的數據再賦值就可以了。還有如果 過多圖表,建議加延遲。要不然容易 卡