僅以此記錄下我的使用echart的方法,畢竟好記性不如爛筆頭。
手摸手,帶你用vue擼後臺 系列三(實戰篇)javascript
npm install echarts --save
vue
"echarts": "^4.2.0-rc.2"
java
export function debounce (func, wait, immediate) { let timeout, args, context, timestamp, result const later = function () { // 據上一次觸發時間間隔 const last = +new Date() - timestamp // 上次被包裝函數被調用時間間隔last小於設定時間間隔wait if (last < wait && last > 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // 若是設定爲immediate===true,由於開始邊界已經調用過了此處無需調用 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } return function (...args) { context = this timestamp = +new Date() const callNow = immediate && !timeout // 若是延時不存在,從新設定延時 if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } }
<template> <div :class="className" :style="{height:height,width:width}"></div> </template> <script> import echarts from 'echarts' import { debounce } from '@/utils' export default { props: { className: { type: String, default: 'chart' }, width: { type: String, default: '100%' }, height: { type: String, default: '350px' }, autoResize: { type: Boolean, default: true }, chartData: { type: Object } }, data () { return {} }, mounted () { this.initChart() if (this.autoResize) { this.__resizeHanlder = debounce(() => { if (this.$chart) { this.$chart.resize() } }, 100) window.addEventListener('resize', this.__resizeHanlder) } }, beforeDestroy () { if (!this.$chart) { return } if (this.autoResize) { window.removeEventListener('resize', this.__resizeHanlder) } this.$chart.dispose() this.$chart = null }, watch: { chartData: { deep: true, handler (val) { this.setOptions(val) } } }, methods: { setOptions (val) { this.$chart.clear() // 清空畫布 this.$chart.setOption(val) }, initChart () { this.$chart = echarts.init(this.$el, 'macarons') this.setOptions(this.chartData) } } } </script>
<template> <div> <charts :chartData="Option"></charts> </div> </template> <script> import Charts from '@/components/Charts' export default { name: 'chartDemo', components: { Charts }, data () { return { Option: {} } }, mounted () { this.getList() }, methods: { getList () { this.Option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line' }] } } } </script>