[英]How to listen to event emitted from 'root' in vue js?
我的应用程序使用 vue.js 并与 vanilla js 进行了一些集成。 在我的 vanilla js 文件中,我创建了一个新的 vue 实例并从那里发出一个名为annotation-click
的事件。 我可以在开发工具选项卡中看到此事件。
这是我制作的自定义事件类:
customevent.js
import Vue from 'vue'
export default window.Event = class Event {
constructor () {
this.vue = new Vue()
}
fire (event, data = null) {
this.vue.$emit(event, data)
}
listen (event, callback) {
this.vue.$on(event, callback)
}
}
在我的 vanilla js
文件中,我发出这样的事件:
import Event from '../utils/customevent'
var test = new Event()
...
handleClick: (view, pos, event) => {
const { schema } = view.state
const attrs = getMarkAttrs(view.state, schema.marks.annotation)
if (attrs.href && event.target instanceof HTMLSpanElement) {
test.fire('notification', {
title: "annotation-joe"
})
}
},
...
该事件是从我的主要 vue.js 应用程序发出的,如下所示:
我正在我的 vue.js 组件中监听事件,但似乎我的监听器没有接收到事件。
如何正确收听<Root>
发出的事件?
我的 vue.js 应用程序导入了 npm 包,我监听这样的事件:
<script>
import Event from "mypackage/utils/customevent";
var test = new Event();
...
created() {
test.listen("notification", function(msg) {
console.log(msg);
});
}
我写了一个例子来实现它:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> {{message}} </div> <button onclick="test()">test</button> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> class MyClass extends EventTarget { doSomething() { this.dispatchEvent(new Event('something')); } } document.getRootNode().instance = new MyClass() function test() { const root = document.getRootNode() root.instance.doSomething(); } var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, created() { const root = document.getRootNode() root.instance.addEventListener('something', (e) => { console.log('Instance fired "something".', e); }); }, }) </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.