uniapp引用echarts的詳細(xì)步驟(附柱狀圖實(shí)例)
相信很多小伙伴對于echarts這個(gè)東西應(yīng)該不會陌生,我在網(wǎng)上看到很多文章,那么他到底是怎么用的呢,卻是五花八門,我現(xiàn)在就來總結(jié)一下我的方法。
如果使用npm全局安裝,太麻煩,這里推薦使用官網(wǎng)(ECharts 在線構(gòu)建)定制下載,這樣會方便我們使用。
選擇柱狀圖,折線圖,餅圖;這三樣是平常較常用到的;
坐標(biāo)系選擇直角坐標(biāo)系;
組件可以全選,也可以選擇自己所需要的,在這里個(gè)人建議除了工具欄不選,其他都選上;下載后的文件為echarts.min.js,建議把他放在static內(nèi)。
好了,來到下一步,我們需要在components內(nèi)創(chuàng)建一個(gè)echarts.vue,把這段代碼復(fù)制下來,放到echarts.vue內(nèi);
<template> <view> <view class="echarts" :prop="option" :change:prop="echarts.update"></view> </view> </template> <script> export default { name: 'Echarts', props: { option: { type: Object, required: true } } } </script> <script module="echarts" lang="renderjs"> export default { data() { return { chart: null } }, mounted() { if (typeof window.echarts === 'object') { this.init() } else { // 動態(tài)引入類庫 const script = document.createElement('script') script.src = './static/echarts.min.js' // script.src = './static/echarts/echarts.min.js' script.onload = this.init document.head.appendChild(script) } }, methods: { /** * 初始化echarts */ init() { this.chart = echarts.init(this.$el) this.update(this.option) }, /** * 監(jiān)測數(shù)據(jù)更新 * @param {Object} option */ update(option) { if (this.chart) { // 因App端,回調(diào)函數(shù)無法從renderjs外傳遞,故在此自定義設(shè)置相關(guān)回調(diào)函數(shù) if (option) { // tooltip if (option.tooltip) { // 判斷是否設(shè)置tooltip的位置 if (option.tooltip.positionStatus) { option.tooltip.position = this.tooltipPosition() } // 判斷是否格式化tooltip if (option.tooltip.formatterStatus) { option.tooltip.formatter = this.tooltipFormatter(option.tooltip.formatterUnit, option .tooltip.formatFloat2, option.tooltip.formatThousands) } } // if (option.xAxis[0].data.length >= 5) { // option.xAxis[0].axisLabel.formatter = function formatter(params) { // if (params > 5) { // return params; // } // var maxLength = 4; // //判斷長度,超出使用...代替 // if (params && params.length > maxLength) { // return params.substring(0, maxLength - 1) + '...'; // } else { // return params; // } // } // } else if(option.xAxis[0].data.length === 1){ // option.xAxis[0].axisLabel.formatter = function formatter(params) { // return params // } // } else { // option.xAxis[0].axisLabel.formatter = function formatter(params) { // if (params > 5) { // return params; // } // var maxLength = 6; // //判斷長度,超出使用...代替 // if (params && params.length > maxLength) { // return params.substring(0, maxLength - 1) + '...'; // } else { // return params; // } // } // } // 設(shè)置新的option this.chart.setOption(option, option.notMerge) } } }, /** * 設(shè)置tooltip的位置,防止超出畫布 */ tooltipPosition() { return (point, params, dom, rect, size) => { //其中point為當(dāng)前鼠標(biāo)的位置,size中有兩個(gè)屬性:viewSize和contentSize,分別為外層div和tooltip提示框的大小 let x = point[0] let y = point[1] let viewWidth = size.viewSize[0] let viewHeight = size.viewSize[1] let boxWidth = size.contentSize[0] let boxHeight = size.contentSize[1] let posX = 0 //x坐標(biāo)位置 let posY = 0 //y坐標(biāo)位置 if (x < boxWidth) { //左邊放不開 posX = 5 } else { //左邊放的下 posX = x - boxWidth } if (y < boxHeight) { //上邊放不開 posY = 5 } else { //上邊放得下 posY = y - boxHeight } return [posX, posY] } }, /** * tooltip格式化 * @param {Object} unit 數(shù)值后的單位 * @param {Object} formatFloat2 是否保留兩位小數(shù) * @param {Object} formatThousands 是否添加千分位 */ tooltipFormatter(unit, formatFloat2, formatThousands) { return params => { let result = '' unit = unit ? unit : '' for (let i in params) { if (i == 0) { result += params[i].axisValueLabel } let value = '--' if (params[i].data !== null) { value = params[i].data // 保留兩位小數(shù) if (formatFloat2) { value = this.formatFloat2(value) } // 添加千分位 if (formatThousands) { value = this.formatThousands(value) } } // #ifdef H5 result += '\n' + params[i].seriesName + ':' + value + ' ' + unit // #endif // #ifdef APP-PLUS result += '<br/>' + params[i].marker + params[i].seriesName + ':' + value + ' ' + unit // #endif } return result } }, /** * 保留兩位小數(shù) * @param {Object} value */ formatFloat2(value) { let temp = Math.round(parseFloat(value) * 100) / 100 let xsd = temp.toString().split('.') if (xsd.length === 1) { temp = (isNaN(temp) ? '0' : temp.toString()) + '.00' return temp } if (xsd.length > 1) { if (xsd[1].length < 2) { temp = temp.toString() + '0' } return temp } }, /** * 添加千分位 * @param {Object} value */ formatThousands(value) { if (value === undefined || value === null) { value = '' } if (!isNaN(value)) { value = value + '' } let re = /\d{1,3}(?=(\d{3})+$)/g let n1 = value.replace(/^(\d+)((\.\d+)?)$/, function(s, s1, s2) { return s1.replace(re, '$&,') + s2 }) return n1 } } } </script> <style lang="scss" scoped> .echarts { width: 100%; height: 100%; } </style>
接下來就可以在所需要使用echarts的頁面上,在script內(nèi)引入該組件,并注冊該組件,注冊完后你需要復(fù)制以下代碼
import echarts from '@/components/echarts.vue'; export default { // 注冊組件 components: { echarts }, data(){ return{ option:{} } }, methods:{ logstatrt() { // console.log('初次調(diào)用'); this.option = { notMerge: true, backgroundColor": "#F8FAFF", tooltip: { trigger: 'axis', showContent: this.showContent, axisPointer: { type: 'shadow', label: { show: true }, }, }, toolbox: { padding: [200, 0, 0, 0], show: true, feature: { //工具配置項(xiàng) mark: { show: true }, dataView: { //數(shù)據(jù)視圖工具,可以展現(xiàn)當(dāng)前圖表所用數(shù)據(jù) show: true, //是否顯示該工具 readOnly: false //是否不可編輯 }, magicType: { show: true, //是否顯示該工具 type: ['line', 'bar'] //啟用的動態(tài)類型 }, restore: { show: true //是否顯示該工具 }, saveAsImage: { show: true //是否顯示該工具 } } }, calculable: false, //是否顯示拖拽的手柄 // itemHeight: 0, legend: { //圖例組件 data: [{ name: '進(jìn)入數(shù)', }, { name: '出去數(shù)' }], itemGap: 24, padding: [16, 0, 0, 0], // y: 'bottom', itemHeight: 8, //高 itemWidth: 8, //寬 icon: 'circle' //設(shè)置為圓 }, grid: { top: '15%', left: '4%', right: '4%', bottom: '6%', containLabel: true }, xAxis: [{ show: true, type: 'category', //坐標(biāo)軸類型 // boundaryGap:false, //解決數(shù)據(jù)與線不對應(yīng)問題 data: ['7.1', '7.2', '7.3', '7.4', '7.5', '7.6', '7.7', '7.8', '7.9', '7.10','7.11' ], // offset:50, //['7.1', '7.2', '7.3', '7.4', '7.5', '7.6', '7.7', '7.8', '7.9', '7.10','7.11', ], //this.xList, //obama_budget_2012.names axisLabel: { color: '#7F84B5', fontWeight: 300, interval: 0, }, axisTick: { show: false //刻度線 }, axisLine: { show: false, //不顯示坐標(biāo)軸線 }, }, ], yAxis: [{ show: true, boundaryGap: false, //解決數(shù)據(jù)與線不對應(yīng)問題 type: 'value', // name: 'Budget (million USD)', // data: this.yList, minInterval: 1, axisLabel: { interval: 0, }, splitLine: { show: true, lineStyle: { //背景網(wǎng)格線 type: 'dashed' } }, axisTick: { show: false //刻度線 }, axisLine: { show: false, //不顯示坐標(biāo)軸線 }, }], dataZoom: [{ show: false, start: 0, end: 100, handleSize: 8 }, { type: 'inside', start: 0, end: 50, }, { show: false, yAxisIndex: 0, filterMode: 'empty', width: 12, height: '80%', showDataShadow: false, left: '93%', handleSize: 8 } ], series: [{ name: '進(jìn)入數(shù)', type: 'bar', data: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'], //['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'], // this.inNum, //obama_budget_2012.budget2011List color: "#00B1FF" }, { name: '出去數(shù)', type: 'bar', data: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'], //['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110','120'], //this.outNum, //obama_budget_2012.budget2012List color: "#FF6C00" } ] }; }, } }
好了,你已經(jīng)離成功不遠(yuǎn)了?。?/p>
接下來我們到頁面上使用該組件,我們要設(shè)置他的id,把option內(nèi)的配置也給他傳過去,該圖的寬高也在上面設(shè)置好,你會發(fā)現(xiàn),這個(gè)時(shí)候多了一個(gè)柱狀圖出來
<echarts :option="option" id="myChart" style="height: 110vw;margin-left: 2vw;width: 100%;padding: 4vw 0 0 0;"></echarts>
這就是一個(gè)簡單的echarts柱狀圖使用 ,我也是走了很多彎路,看了許多的文章,覺得每個(gè)人的方法都不同,我只是把我認(rèn)為好的方法放上來,希望對大家有所幫助。
最后附上一張效果圖 (當(dāng)然,這些顏色都是可改的,具體可以看文檔或者來問一下我,我都非常樂意解答)
附:報(bào)錯(cuò):this.echarts.setCanvasCreator is not a function 的解決辦法
echarts.vue頁面引起的 prors不能傳遞方法
將剛才定制的echarts.js文件引入進(jìn)去
import * as echarts from '@/common/echarts.min.js';
參數(shù)加this
this.ctx = wx.createCanvasContext(canvasId,this); ? const query = wx.createSelectorQuery().in(this); ?
也可以直接復(fù)制代碼進(jìn)去,注意修改echarts.js的路徑
<template> <canvas v-if="canvasId" class="ec-canvas" :id="canvasId" :canvasId="canvasId" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" @error="error"></canvas> </template> <script> import WxCanvas from './wx-canvas'; import * as echarts from '@/common/echarts.min.js'; export default { props: { // echarts: { // required: true, // type: Object, // default() { // return echarts; // } // }, onInit: { required: true, type: Function, default: null }, canvasId: { type: String, default: 'ec-canvas' }, lazyLoad: { type: Boolean, default: false }, disableTouch: { type: Boolean, default: false }, throttleTouch: { type: Boolean, default: false } }, onReady() { this.echarts = echarts; if (!this.echarts) { console.warn('組件需綁定 echarts 變量,例:<ec-canvas id="mychart-dom-bar" ' + 'canvas-id="mychart-bar" :echarts="echarts"></ec-canvas>'); return; } console.log('echarts'); console.log(this.onInit); if (!this.lazyLoad) this.init(); }, methods: { init() { const version = wx.version.version.split('.').map(n => parseInt(n, 10)); const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9) || (version[0] === 1 && version[1] === 9 && version[2] >= 91); if (!isValid) { console.error('微信基礎(chǔ)庫版本過低,需大于等于 1.9.91。' + '參見:https://github.com/ecomfe/echarts-for-weixin' + '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82'); return; } if (!this.onInit) { console.warn('請傳入 onInit 函數(shù)進(jìn)行初始化'); return; } const canvasId = this.canvasId; this.ctx = wx.createCanvasContext(canvasId,this); const canvas = new WxCanvas(this.ctx, canvasId); this.echarts.setCanvasCreator(() => canvas); const query = wx.createSelectorQuery().in(this); query .select(`#${canvasId}`) .boundingClientRect(res => { if (!res) { //setTimeout(() => this.init(), 200); return; } this.chart = this.onInit(canvas, res.width, res.height); }) .exec(); }, canvasToTempFilePath(opt) { const { canvasId } = this; this.ctx.draw(true, () => { wx.canvasToTempFilePath({ canvasId, ...opt }); }); }, touchStart(e) { const { disableTouch, chart } = this; if (disableTouch || !chart || !e.mp.touches.length) return; const touch = e.mp.touches[0]; chart._zr.handler.dispatch('mousedown', { zrX: touch.x, zrY: touch.y }); chart._zr.handler.dispatch('mousemove', { zrX: touch.x, zrY: touch.y }); }, touchMove(e) { const { disableTouch, throttleTouch, chart, lastMoveTime } = this; if (disableTouch || !chart || !e.mp.touches.length) return; if (throttleTouch) { const currMoveTime = Date.now(); if (currMoveTime - lastMoveTime < 240) return; this.lastMoveTime = currMoveTime; } const touch = e.mp.touches[0]; chart._zr.handler.dispatch('mousemove', { zrX: touch.x, zrY: touch.y }); }, touchEnd(e) { const { disableTouch, chart } = this; if (disableTouch || !chart) return; const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {}; chart._zr.handler.dispatch('mouseup', { zrX: touch.x, zrY: touch.y }); chart._zr.handler.dispatch('click', { zrX: touch.x, zrY: touch.y }); } } }; </script> <style scoped> .ec-canvas { width: 100%; height: 100%; flex: 1; } </style>
總結(jié)
到此這篇關(guān)于uniapp引用echarts的詳細(xì)步驟的文章就介紹到這了,更多相關(guān)uniapp引用echarts內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript 節(jié)流函數(shù) Throttle 詳解
這篇文章主要為大家詳細(xì)介紹了JavaScript 節(jié)流函數(shù) Throttle,感興趣的小伙伴們可以參考一下2016-07-07js實(shí)現(xiàn)Tab選項(xiàng)卡切換效果
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)Tab選項(xiàng)卡切換效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10js實(shí)現(xiàn)調(diào)用網(wǎng)絡(luò)攝像頭及常見錯(cuò)誤處理
這篇文章主要介紹了js實(shí)現(xiàn)調(diào)用網(wǎng)絡(luò)攝像頭及常見錯(cuò)誤處理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03js 動態(tài)添加標(biāo)簽(新增一行,其實(shí)很簡單,就是幾個(gè)函數(shù)的應(yīng)用)
把所有代碼拷下另存為一個(gè)html文件,在瀏覽器中打開,點(diǎn)擊“新增一行”按鈕就可以,以下是對js函數(shù)的解釋2009-03-03如何用JavaScript實(shí)現(xiàn)動態(tài)修改CSS樣式表
如何用JavaScript實(shí)現(xiàn)動態(tài)修改CSS樣式表?下面小編就為大家?guī)硪黄狫avaScript實(shí)現(xiàn)動態(tài)修改CSS樣式表的方法。希望對大家有所幫助。一起跟隨小編過來看看吧2016-05-05用xhtml+css寫的相冊自適應(yīng) - 類似九宮格[兼容 ff ie6 ie7 opear ]
用xhtml+css寫的相冊自適應(yīng) - 類似九宮格[兼容 ff ie6 ie7 opear ]...2007-05-05js+css3實(shí)現(xiàn)簡單時(shí)鐘特效
這篇文章主要為大家詳細(xì)介紹了js+css3實(shí)現(xiàn)簡單時(shí)鐘特效,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09