我想为一个项目做出贡献,这个项目是用Vue编写的,而我在Vue方面是一个初学者。
我有两个组件 - Setup
和MainApp
两个组件都需要根据websocket中不同的消息更新一些状态。一些websocket消息会影响前者,一些则影响后者。
Vue不知道服务,所以我想创建一个自定义组件,其中包含空的<template>
。在那里实例化websocket,然后每次监听器中发生新消息时发出this.emit()
。
其他两个组件将侦听发出的信号,并能够做出反应。
不幸的是,我无法使websocket组件正常工作。
main.js:
import Ws from './WsService.vue';
//other imports
const routes = [
//routes
]
const router = new VueRouter({
routes // short for `routes: routes`
})
const app = new Vue({
router
}).$mount('#app')
//I thought this to be the way to instantiate my webSocket service:
const WsService = new Vue({
el: '#WsService',
components: { Ws }
});
index.html
<body>
<div id="app">
<div id="WsService"></div>
<router-link to="/setup">Setup</router-link>
<router-link to="/main-app">Main App</router-link>
<router-view></router-view>
</div>
<script src="/dist/demo-app.js"></script>
</body>
WebSocket "服务":
<template>
</template>
<script>
const PORT_LOCAL = 9988;
var ws = new WebSocket("ws://localhost:" + PORT_LOCAL);
ws.onopen = function() {
ws.send('{"jsonrpc":"2.0","id":"reg","method":"reg","params":null}');
};
ws.onerror = function(e) {
console.log("error in WebSocket connection!");
console.log(e);
};
export default {
data() {
return {
}
},
created() {
var self = this;
ws.onmessage = function(m) {
var msg = JSON.parse(m.data);
switch(msg.id) {
// result for address request
case "reg":
self.$emit("reg_received", msg.result);
break;
case "send":
self.$emit("send_received", msg.result);
break;
case "subscribe":
self.$emit("subscribe_received", msg.result);
break;
default:
console.log(msg);
break;
}
}
},
methods: {
},
send(id, method, params) {
ws.send('{"jsonrpc":"2.0","id":"' + id + '","method":"' + method + '","params":null}');
}
}
}
</script>
例如从主应用程序发送(这似乎有效):
import WsSvc from './WsService.vue';
export default {
data() {
//
},
subscribe() {
let jsonrpc = "the jsonrpc string";
WsSvc.send(jsonrpc);
}
}
听取emit
:
export default {
data() {
//
},
created() {
this.$on("reg_received", function(result){
//do smth with the result
});
}
}
使用这个配置,
created
钩子实际上永远不会被调用,因此我永远不会命中onmessage
监听器。我认为要使用自定义组件的原因是我可以访问emit
函数。感觉我正在把它变得比应该的更复杂,但我还没有成功。解决方案不需要遵循这种方法。