【发布时间】:2018-03-22 11:42:24
【问题描述】:
我想为一个项目做出贡献 - 它是用 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 函数。
感觉我让它变得比它应该的更复杂,但我还没有设法让它正确。解决方案不需要遵循这种方法。
【问题讨论】:
-
“Vue 不知道服务”。这真的不正确。只需构建您的 API 并将其导入到您要使用它的组件中。这里不需要组件。
-
@Bert 也许你是对的,但问题不是 API,而是如何从
onmessage回调并更新其他组件的属性。 -
这个怎么样? codesandbox.io/s/4wp90vvr2w
-
@Bert 我并没有完全解决它,但你的链接让我有预感来解决它。如果您想提供它作为答案,我会接受。谢谢!
标签: javascript vue.js vuejs2 vue-component