需求:echarts图表需要加入点击事件,项目是用指令使用echarts,并没有在页面实例echarts图表,那就需要一个统一的传参来实现:
1、话不多说上代码:
import Vue from 'vue'
const echarts = require('echarts')
/**
* 变量说明:
* el: html element,el=document.getElementById得到值
* binding:绑定变量。其中binding.value值为对象时即为echarts的option;值为数组时,索引0为echarts的option,索引1为echarts的event
* vnode:vue的虚拟节点
*/
export default {
deep: true,
bind(el, binding, vnode) {
// do nothing
},
inserted(el, binding, vnode) {
const self = vnode.context
Vue.nextTick(() => {
// options & events
let [options, events] = [{}, {}]
if (Array.isArray(binding.value)) {
options = binding.value[0] || {}
events = binding.value[1] || {}
} else {
options = binding.value || {}
}
// init chart
self._echartsInstance = echarts.init(el, theme)
self._echartsInstance.showLoading()
self._echartsInstance.setOption(options, true)
self._echartsInstance.hideLoading()
setTimeout(() => {
self._echartsInstance.resize()
}, 0)
// init chart events
Object.keys(events).forEach(key => {
const func = events[key]
if (typeof func === 'function') {
self._echartsInstance.on(key, params => {
func(params)
})
}
})
})
},
update(el, binding, vnode) {
const self = vnode.context
Vue.nextTick(() => {
// options & events
let options = {}
if (Array.isArray(binding.value)) {
options = binding.value[0] || {}
} else {
options = binding.value || {}
}
// init chart
self._echartsInstance = echarts.init(el, theme)
self._echartsInstance.showLoading()
self._echartsInstance.setOption(options, true)
self._echartsInstance.hideLoading()
setTimeout(() => {
self._echartsInstance.resize()
}, 0)
})
},
componentUpdated(el, binding, vnode) {
// do nothing
},
unbind(el, binding, vnode) {
const self = vnode.context
try {
if (self._echartsInstance) {
// console && console.log('in echarts unbind......')
self._echartsInstance.dispose()
}
} catch (e) {}
}
}
main.js里
Vue.directive('echarts', echartsOption)
页面内的使用:
1、templeate里用v-echarts绑定计算属性
<template>
<div>
<div v-if="ready" :style="chartStyle" v-echarts="echartsOptions"></div>
</div>
</template>
<script>
export default {
data() {
const self = this
return {
ready: false,
options: null,
events: {
click(params) {
self.onEchartsClick(params)
}
}
}
},
computed: {
echartsOptions() {
//传入两个参数,1为图表,2为事件
return [this.options, this.events]
}
},
methods: {
//事件返回的参数,在这里操作就ok了
onEchartsClick(params) {
console.log(params)
},
load() {
let option={
//你定义的图表
}
this.options = option
this.$nextTick(() => {
this.ready = true;
});
}
},
mounted() {
this.load()
},
}
</script>
对你有帮助的话点个赞吧。