如何将 websocket 实例传递给 vue.js 组件,然后在其上调用 send()?
Posted
技术标签:
【中文标题】如何将 websocket 实例传递给 vue.js 组件,然后在其上调用 send()?【英文标题】:How do I pass websocket instance to vue.js components and then call send() on it? 【发布时间】:2017-12-28 10:27:09 【问题描述】:单击按钮时,我正在尝试调用 send 并通过 Web 套接字向服务器发送消息:
// HelloWorld.vue
<template>
<div class="hello">
<h1> msg </h1>
<button v-on:click="send($event)">Send</button>
</div>
</template>
<script>
export default
name: 'HelloWorld',
props: ['socket'],
data()
return
msg: 'Welcome to Your Vue.js App',
;
,
methods:
send: () =>
this.socket.addEventListener('open', () =>
this.socket.send('Hello Server!');
);
,
,
;
</script>
// App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view :socket="ws"/>
</div>
</template>
<script>
export default
name: 'app',
created()
this.ws = new WebSocket('ws://localhost:3000/websocket');
,
;
</script>
点击发送按钮时出现的错误是:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
at VueComponent.send (HelloWorld.vue?cc3a:19)
at Proxy.boundFn (vue.esm.js?efeb:190)
at click (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?"id":"data-v-469af010","hasScoped":true,"transformToRequire":"video":["src","poster"],"source":"src","img":"src","image":"xlink:href","buble":"transforms":!./node_modules/vue-loader/lib/selector.js?type=template&index=0&bustCache!./src/components/HelloWorld.vue (app.js:905), <anonymous>:13:17)
at invoker (vue.esm.js?efeb:2004)
at htmlButtonElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1802)
【问题讨论】:
【参考方案1】:尝试在全局窗口范围内创建套接字实例。它将在安装 Vue 应用程序之前创建,并且可以在您的应用程序中访问。
App.vue
<script>
window.socket = new WebSocket('ws://localhost:3000/websocket');
export default
name: 'app'
;
</script>
HelloWorld.vue
methods:
send: () =>
window.socket.addEventListener('open', () =>
window.socket.send('Hello Server!');
);
,
,
【讨论】:
如果我不需要立即连接怎么办?以上是关于如何将 websocket 实例传递给 vue.js 组件,然后在其上调用 send()?的主要内容,如果未能解决你的问题,请参考以下文章
如何将 $_SESSION 变量传递给 websocket 服务器?
如何将活动WebSocket传递给Node.js中的集群线程?