I am attempting to send a message via a web socket to the server when a button is clicked:
// HelloApp.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button v-on:click="sendMessage($event)">Send Message</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['socket'],
data() {
return {
msg: 'Welcome to Your Vue.js App',
};
},
methods: {
sendMessage: () => {
this.socket.addEventListener('open', () => {
this.socket.send('Hello Server!');
});
},
},
};
</script>
// MainApp.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>
When I try to click the button to send the message, I encounter this error:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
at VueComponent.sendMessage (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)