我的应用程序使用vue.js并与Vanilla js进行了一些集成。在我的普通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)
}
}
在我的原始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>
发出的事件?
导入了npm包的vue.js应用程序,我像这样监听事件:
<script>
import Event from "mypackage/utils/customevent";
var test = new Event();
...
created() {
test.listen("notification", function(msg) {
console.log(msg);
});
}
答案 0 :(得分:1)
我写了一个例子来实现它:
<!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>