uniapp引用echarts的詳細步驟(附柱狀圖實例)
相信很多小伙伴對于echarts這個東西應(yīng)該不會陌生,我在網(wǎng)上看到很多文章,那么他到底是怎么用的呢,卻是五花八門,我現(xiàn)在就來總結(jié)一下我的方法。
如果使用npm全局安裝,太麻煩,這里推薦使用官網(wǎng)(ECharts 在線構(gòu)建)定制下載,這樣會方便我們使用。
選擇柱狀圖,折線圖,餅圖;這三樣是平常較常用到的;

坐標系選擇直角坐標系;

組件可以全選,也可以選擇自己所需要的,在這里個人建議除了工具欄不選,其他都選上;下載后的文件為echarts.min.js,建議把他放在static內(nèi)。

好了,來到下一步,我們需要在components內(nèi)創(chuàng)建一個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)前鼠標的位置,size中有兩個屬性: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坐標位置
let posY = 0 //y坐標位置
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: { //工具配置項
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: '進入數(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', //坐標軸類型
// 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, //不顯示坐標軸線
},
}, ],
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, //不顯示坐標軸線
},
}],
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: '進入數(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)離成功不遠了??!
接下來我們到頁面上使用該組件,我們要設(shè)置他的id,把option內(nèi)的配置也給他傳過去,該圖的寬高也在上面設(shè)置好,你會發(fā)現(xiàn),這個時候多了一個柱狀圖出來
<echarts :option="option" id="myChart" style="height: 110vw;margin-left: 2vw;width: 100%;padding: 4vw 0 0 0;"></echarts>
這就是一個簡單的echarts柱狀圖使用 ,我也是走了很多彎路,看了許多的文章,覺得每個人的方法都不同,我只是把我認為好的方法放上來,希望對大家有所幫助。
最后附上一張效果圖 (當(dāng)然,這些顏色都是可改的,具體可以看文檔或者來問一下我,我都非常樂意解答)

附:報錯:this.echarts.setCanvasCreator is not a function 的解決辦法
echarts.vue頁面引起的 prors不能傳遞方法
將剛才定制的echarts.js文件引入進去
import * as echarts from '@/common/echarts.min.js';
參數(shù)加this
this.ctx = wx.createCanvasContext(canvasId,this); ? const query = wx.createSelectorQuery().in(this); ?
也可以直接復(fù)制代碼進去,注意修改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ù)進行初始化');
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的詳細步驟的文章就介紹到這了,更多相關(guān)uniapp引用echarts內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
uniapp改變底部安全區(qū)頂部手機信號時間電池欄顏色樣式
這篇文章主要為大家介紹了uniapp改變底部安全區(qū)頂部手機信號時間電池欄顏色樣式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
confirm確認對話框的實現(xiàn)方法總結(jié)
下面小編就為大家?guī)硪黄猚onfirm確認對話框的實現(xiàn)方法總結(jié)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
Windows下支持自動更新的Electron應(yīng)用腳手架的方法
這篇文章主要介紹了Windows下支持自動更新的Electron應(yīng)用腳手架的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
JavaScript計算器網(wǎng)頁版實現(xiàn)代碼分享
這篇文章主要為大家詳細介紹了JavaScript計算器網(wǎng)頁版實現(xiàn)代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07
JavaScript第七種數(shù)據(jù)類型Symbol的用法詳解
Symbol是ES6中引入的一種新的基本數(shù)據(jù)類型,用于表示一個獨一無二的值。它是JavaScript中的第七種數(shù)據(jù)類型。本文將詳細講講Symbol的使用,需要的可以參考一下2022-09-09
JavaScript+html5 canvas實現(xiàn)本地截圖教程
這篇文章主要為大家詳細介紹了JavaScript+html5 canvas實現(xiàn)本地截圖教程,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-02-02

