What is the best way to pass a websocket instance to Vue.js components and then invoke the send() method on it?

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)

Answer №1

To ensure the socket instance is available throughout your Vue app, consider creating it in the global window scope. By doing so, the socket will be initialized before the Vue app is mounted and can be easily accessed from any component.

Here's an example implementation:

<script>
 window.socket = new WebSocket('ws://localhost:3000/websocket');
 export default {
    name: 'app'
 };
</script>

If you want to use the socket in a specific component like HelloWorld.vue, you can do so by referencing the global socket object:

methods: {
  send: () => {
    window.socket.addEventListener('open', () => {
      window.socket.send('Hello Server!');
    });
  },
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Add a new key-value pair to the mock data by clicking on it

Hey there! I'm currently tackling a task that involves toggling the value of a boolean and then appending a new key-value pair on click. I've been attempting to use the . operator to add the new key-value pair, but it keeps throwing an error. In ...

“Unlocking the secret to extracting color from an image in React Native”

While it may sound like a silly question, I am new to the world of React technology. I am looking to extract colors from an image - for example, when a user selects an image to upload, I want to identify all the colors used in that image. If this is possib ...

When accessing req.param on the server side in a Node.js application, it returns undefined

I am currently utilizing nodejs and angularjs for my project. In the client-side javascript file, I made a GET request to the nodejs server with necessary data in parameters. itinerary.js $http({ method : "GET", url : '/createItinerary&apo ...

Is utilizing React function components the most effective solution for this problem?

export default function loginUserUsing(loginType: string) { const [state, setState] = useState(loginType); function login() { // body of the login function } function oauth() { // body of the oauth function login(); ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

What is the best way to transmit a Blob object to the server without it arriving empty?

I'm currently facing an issue where I am attempting to send a Blob object containing video data to my server for upload to my S3 storage. However, the Blob is arriving as an empty object on the server side. const blob = new Blob(videoChunks, { t ...

Expanding a class functionality by incorporating a method through .prototype

My goal is to define a class called "User" and then add a method to the class using the "prototype" keyword. I want the method "who_auto" to be accessible to all future instances of "User". When testing this code in JSFiddle, I encountered the error messa ...

Guide on incorporating a customized HTML tag into ckeditor5

Can someone help me with integrating CKEditor and inserting HTML tag of a clicked image into the editor? I've tried different solutions but haven't been successful. I understand that doing this directly in CKEditor may not be secure. This is a V ...

Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports. $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... }; My challenge is sorting these items by sport name: <ul> ...

"Encountered an error: AngularJS is unable to read the property 'push' as it is

I'm attempting to generate an array using data retrieved from an API. However, I continue to encounter an error message stating cannot read property 'push' of undefined in Javascript. Could someone please guide me on how to resolve this iss ...

React Form with Conditional Input Options and Validation

Just diving into the world of React, I find myself connecting a React frontend to a Flask backend in a group project. Surprisingly, I've ended up handling about 90% of the workload. While I have utilized MUI for implementing fields, my focus is more o ...

Retrieve information from deeply nested JSON and showcase using Vue-Multiselect

My goal is to fetch data from the server and present it in Multiselect using nested JSON, which can be done through Vue-Multiselect. Once displayed, I should have the ability to add new tags as needed, essentially updating the data. While I can display o ...

Hide <a> by setting its display property to none

Below is the HTML code: <td> <a class="link" href="#"> <span class="download">Link</span> </a> <a class="link" href="#"> <span class="csvdownload">Link 2</span> </a> </td> I am lo ...

The argument 'TabsCtrl1' is throwing an error as it is not recognized as a valid function and is showing as

I have encountered a problem with my controller, and I am seeing the following error message: Error: [ng:areq] Argument 'TabsCtrl1' is not a function, got undefined http://errors.angularjs.org/1.3.0-beta.11/ng/areq?p0=TabsCtrl1&p1=not%20a%20 ...

JavaScript | Determining the coordinates of where on the image X and Y were clicked

My goal is to determine the position of an x and y location when a user clicks on an image. This information will be used to add a spot to the image that displays relevant information. The content for the spot will be dynamically loaded from a SQL database ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...

Is there a way for me to retrieve a collection of objects that have been added to an array in Vue.js?

Kindly review the following codes: sidebar_components: [ { title: "Admin Management", href: "javascript:void(0)", idAcc: "accordion-1", value: ["this is a test 1", "this is test 2&q ...

Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in de ...