fab*_*ous 5 javascript vue.js vue-component vuejs2
我想为一个项目做贡献 - 它是用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 }
});
Run Code Online (Sandbox Code Playgroud)
的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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
例如从主应用程序发送(这似乎工作):
import WsSvc from './WsService.vue';
export default {
data() {
//
},
subscribe() {
let jsonrpc = "the jsonrpc string";
WsSvc.send(jsonrpc);
}
}
Run Code Online (Sandbox Code Playgroud)
听emit:
export default {
data() {
//
},
created() {
this.$on("reg_received", function(result){
//do smth with the result
});
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种配置,created钩子实际上永远不会被调用 - 因此我永远不会碰到onmessage听众.我认为有一个自定义组件的原因是我可以访问该emit功能.
感觉我让它变得比它应该更复杂,但我还没有设法做到这一点.解决方案不需要遵循这种方法.
在这种情况下,不需要特定于套接字的组件.我过去在几个项目中所做的是实现一个API或存储对象来处理套接字消息,然后将该API或存储导入到需要它的组件中.同样在类似的答案中,我将展示如何将WebSocket与Vuex集成.
下面是一个示例,它将使用Vue作为事件发射器的概念与可以导入任何组件的Web套接字相结合.该组件可以订阅和收听它想要收听的消息.以这种方式包装套接字将原始套接字接口抽象出去,并允许用户以更典型的Vue方式使用$ on/$ off订阅.
Socket.js
import Vue from "vue"
const socket = new WebSocket("wss://echo.websocket.org")
const emitter = new Vue({
methods:{
send(message){
if (1 === socket.readyState)
socket.send(message)
}
}
})
socket.onmessage = function(msg){
emitter.$emit("message", msg.data)
}
socket.onerror = function(err){
emitter.$emit("error", err)
}
export default emitter
Run Code Online (Sandbox Code Playgroud)
以下是组件中使用的代码示例.
App.vue
<template>
<ul>
<li v-for="message in messages">
{{message}}
</li>
</ul>
</template>
<script>
import Socket from "./socket"
export default {
name: 'app',
data(){
return {
messages: []
}
},
methods:{
handleMessage(msg){
this.messages.push(msg)
}
},
created(){
Socket.$on("message", this.handleMessage)
},
beforeDestroy(){
Socket.$off("message", this.handleMessage)
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
这是一个有效的例子.