使用clickedOutside.js(点击其他区域执行方法)来触发echarts的dispatchAction方法
1、在src目录的plugins创建clickedOutside.js文件
// Polyfill for Event.path in IE 11: https://stackoverflow.com/a/46093727
function getParents(node, memo) {
const parsedMemo = memo || [];
const { parentNode } = node;
if (!parentNode) {
return parsedMemo;
}
return getParents(parentNode, parsedMemo.concat(parentNode));
}
// Click-outside by BosNaufal: https://github.com/BosNaufal/vue-click-outside
export default {
bind(el, binding, vNode) {
// Provided expression must evaluate to a function.
console.log(el);
if (typeof binding.value !== "function") {
const compName = vNode.context.name;
let warn = `[Vue-click-outside:] provided expression ${binding.expression} is not a function, but has to be`;
if (compName) {
warn += `Found in component ${compName}`;
}
console.warn(warn);
}
// Define Handler and cache it on the element
const { bubble } = binding.modifiers;
const handler = (e) => {
// Fall back to composedPath if e.path is undefined
const path =
e.path ||
(e.composedPath ? e.composedPath() : false) ||
getParents(e.target);
if (bubble || (path.length && !el.contains(path[0]) && el !== path[0])) {
binding.value(e);
}
};
el.__vueClickOutside__ = handler;
// add Event Listeners
document.addEventListener("click", handler);
},
unbind(el) {
// Remove Event Listeners
document.removeEventListener("click", el.__vueClickOutside__);
el.__vueClickOutside__ = null;
},
};
2、mian.js导入clickedOutside.js注册成指令
import VueClickOutSide from '../src/plugins/clickedOutside.js';
Vue.directive('click-outside', VueClickOutSide)
3、在组件中使用
<div v-click-outside="hasClickedOutsideBoxy" class="wallet-echarts" id="walletEcharts"></div>
export default {
data(){
return {
myChart: null
}
},
methods: {
createEcharts(){
let chartDom = document.getElementById("walletEcharts");
this.myChart = this.$echarts.init(chartDom);
let option
// option 配置根据自己的项目配置相应的配置项即可
option && this.myChart.setOption(option);
},
hasClickedOutsideBoxy(){
if(this.myChart){
this.myChart.dispatchAction({
type:'hideTip'
})
}
}
}
}