有个小项目在原来原生的框架编写,但是不想写原生,就引入了vue
然后有个需求要和原生的js进行交互通讯,于是就可以用node.js EventEmitter
具体做法:
先引入文件<script src="../../js/eventEmitter.js"></script>,
初始化,
然后在vue里面发送emit,
在外面监听on
var event = new EventEmitter(); $(document).ready(function () { //监听some_event事件 event.on('some_event', function (data) { }); }) let vm = new Vue({ el: "#app", methods: { getList() { // 触发事件 event.emit('some_event','params'); }, } });
附上eventEmitter.js
class EventEmitter { constructor() { this.event = {}; this.maxListerners = 10; } // 监听 on(type, listener) { if (this.event[type]) { if (this.event[type].length >= this.maxListerners) { console.error('同一个监听器最多被十个对象监听,否则可能造成内存泄漏. '); return; } if (!this.event[type].includes(listener)) { this.event[type].push(listener); } } else { this.event[type] = [listener]; } } //发送监听 emit(type, ...rest) { if (this.event[type]) { this.event[type].map(fn => fn.apply(this, rest)); } } //移除监听器 removeListener(type,func) { if (this.event[type]) { this.event[type] = this.event[type].filter(item => item !== func); if (this.event[type].length === 0) { delete this.event[type]; } } } //移除所有的监听器 removeAllListener() { this.event = {}; } }