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

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

Exploring the possibilities of JavaScript within the IntelliJ REST client

I've delved into the extensive documentation provided by JetBrains on their HTTP Client and how to incorporate requests using files with a .http extension. The challenge I'm facing involves utilizing a function from a separate .js file within on ...

Get a list of all languages supported by browsers using JavaScript

Within my HTML user interface, I have a dropdown that needs to display a list of all installed browser languages except for the first one. I managed to retrieve the first language (en-us), but I also have the zh-CN Chinese pack installed on my operating s ...

Is it possible to initially design a login page using HTML/CSS and JavaScript, and then integrate VUE into it?

As part of a school project, I am tasked with developing a web-based application for a library system. The goal is to create a platform where librarians can login and manage books by adding, removing, or editing them. My responsibility lies in handling the ...

Is there a way to reduce the excessive bottom margin on Twitter embeds?

Is there a way to adjust the Twitter embed code for tweets so they don't have a large margin at the bottom? Here is an example of the standard Twitter embed code: <blockquote class="twitter-tweet"><p>@<a href="https://twitter.com/gami ...

The #each helper in Handlebars is used to iterate over an array

I have a function that generates an array as output. I am looking for a way to iterate over this array using the each method. Can anyone provide guidance on how to achieve this? Consider if the handlebars helper produces the following array: details: [{ ...

Using Vue.js with jQuery plugins: A step-by-step guide

Currently in the process of rewriting code to Vue.js, I am interested in incorporating some Jquery plugins, but I am uncertain about the correct method. One plugin I would like to utilize is a scrollbar: I understand that initialization should look someth ...

Passing events from a VueJs 3 grandchild component to its grandparent component

I'm still getting the hang of Vue and diving into my initial project. I'm currently focusing on constructing a form that involves multiple child and grandchild components. The issue arose when I realized I needed to generate multiple copies of th ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Working with Typescript to map and sort the key values of a new datasource object

Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of t ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

Can you explain the significance behind the error message "RangeError: Invalid status code: 0"?

Currently, I'm trying to understand the workings of express and have come up with this get method: app.get('/myendpoint', function(req, res) { var js = JSON.parse ({code: 'success', message:'Valid'}); res.status( ...

What is the best method for gathering information from multiple input fields?

I'm currently working on developing a Polymer application that includes a search button with multiple input boxes. I want the search operation to consider all the inputs from these boxes when performing a search. Here is an image depicting the scenar ...

Collaboratively utilizing resources among various NPM Workspaces

Currently, I am working on a React project using NPM Workspaces. I have created an 'assets' workspace within this project to store all images and assets that need to be accessed by other workspaces. The directory structure of the project is as fo ...

Exploring ways to incorporate mouse movements into this simple JavaScript script

I have recently decided to convert my JavaScript code into jQuery code to incorporate mouse events. After downloading the latest version of jQuery and renaming it as "jquery.js," I made modifications to my manifest.json file by adding "jquery.js." However, ...

Array-based input validation

Is there a way to validate an input field against a list of strings in an array without using custom directives or patterns? For example, if the array contains town, city, and house, then typing any of those words should result in a validation failure. An ...

Changing the port of an https (http) URL: A step-by-step guide

Initially, I have a website set up on nginx and Ubuntu 20.04 running on port 80 for http and port 443 for https, accessible through the URL https://mysite.cc (It is functioning correctly). Now, I am looking to add another site using Spring Cloud (Docker) ...

Detailed enrollment procedure

I am facing an issue with the code in my HTML that validates input types. The system detects empty fields and prevents proceeding to the next step. How can I disable this validation as some of the fields are not required? For instance, the input type < ...

When viewing on mobile devices, the hover effect in responsive web design

While working on a responsive website, I encountered some challenges. I have a Div containing an image and some information. When a user hovers over this div, the background changes and 3 buttons appear. However, the issue arises when using a mobile devi ...

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...