Accessing data from a Vue component externally

Utilizing Vue loaded from a script (not a CLI) in a file named admin.js, I have multiple components that interact with each other by emitting events. No Vuex is used in this setup. Additionally, there is another file called socket which creates a websocket and an onmessage event listener, completely separate from the Vue components.

Vue components can utilize the socket as it is defined like so:

var Socket = new WebSocket(wsServer + ":" + wsPort);

Since it is created in the main scope, all Vue components can access it for functionalities such as:

Socket.send({ ... })

In some scenarios, it may be necessary to analyze data from the socket and respond with data from multiple components.

I have considered two solutions for handling these situations:

  1. In each component that needs to wait for data from the socket, add an event listener and call internal methods of the components based on the commands received. This approach involves sending data from the socket to components and reacting accordingly. However, this method could lead to complications due to event listeners multiplying and difficulties in managing them.

  2. Retrieve data directly from components through the socket. In this case, when a specific message is received in the event listener onmessage, check the components for the required data and react accordingly.

This process would look something like this:

Socket.onmessage = function(e) {
    let json = JSON.parse(e.data);
    if (json.cmd == "CALLDATA") {
        // Retrieve data from Vue component
        let obj = objectized data from the component 
        Socket.send(obj)
    }
}

Now, the question arises:

How (or is it even possible) to retrieve data from one or more components from outside of Vue Components?

Answer №1

Incorporate a straightforward plugin to encapsulate the socket and manage message transmission/reception. After setting up the components, integrate the plugin using Vue.use(MySocketPlugin), making it accessible in each component through a custom name like this.$mySocketPlugin.

this.$mySocketPlugin.onmessage('some-message', function (payload) {
     // process payload here
})

this.$mySocketPlugin.send('some-other-message', data)    

Alternatively, establish a global mixin containing the essential functions for data exchange. Both approaches are quite similar, so it simply depends on your personal preference.

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

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

Creating Vue methods functions in separate JavaScript files

Hi there, I'm new to this so please forgive me if my question seems silly. I have a vue component called vuu /path_to_main/vue_file/app.js const vuu = new Vue({ el: '#vuu', data: { latitude: 'longi', long ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

Showcasing ranges from various input types on a single page

I have a challenge in displaying the values of multiple sliders on my webpage. Here's the code snippet I've been working on: var i = 0; var st = 'slider'; var ot = 'output'; var s = ''; var o = ''; for ...

The index type 'X' is not allowed for use in this scenario

I encountered an issue in my TypeScript code: error message: 'Type 'TransitionStyles' cannot be used as an index type.' I'm wondering if there's a way to modify my interface so that it can be used as an index type as well: ...

The building of the module was unsuccessful due to a failure in the babel-loader located in the webpack module of Nuxt

While working on my Nuxt.js project, I encountered a warning error that I couldn't resolve even after searching for a solution. If anyone can assist me with this issue, it would be greatly appreciated. The error message is as follows: ERROR in ./.nu ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Having trouble implementing String.prototype in my factory

Currently, I am working on incorporating a function mentioned in this answer. String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b]; return typeof r === 's ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

Adjust the value of a select box to the chosen option using JQuery

Could someone please assist me with this code? I am trying to adapt it for use on my mobile device with jQuery Mobile. var obj = jQuery.parseJSON(finalresult); //alert(obj); var dept = '2'; $(document).ready(function () { //$("#opsContactId ...

For the past 8 hours, my main focus has been on successfully transmitting a basic JSON object containing data from an API from my Express backend to a React component

I have been trying to achieve my initial goal of retrieving data from the API I am using on the backend, inserting that data into my database, and then sending that data through res.json so it can be accessed on the frontend via fetch. Despite all my attem ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. Here's the full page code: Yo ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...

Ways to efficiently group and aggregate data in JavaScript, inspired by LINQ techniques

I'm feeling overwhelmed by this. Could you lend a hand? Consider the following .NET classes: Teacher: public class Teacher { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } publ ...

Randomly selecting an element from an array as the default option in vue.js

I am working on a neat little tool to learn vue.js where users can find out the time it takes to travel from one location to another: Codepen It's functioning fairly well at the moment, but I want to include a random value from each array when the pa ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

What is the best way to retrieve a specific number of documents from MongoDB?

I am currently facing an issue with my code that is returning all news related to a company. However, I only want the first 15 elements. Is there a way to achieve this? The following code snippet retrieves all news for a company using the google-news-jso ...

React.js: Endless rendering occurs when using setState as a callback function, even after props have been destructured

Issue I am facing a problem with my child component that receives button id-name configurations as props. It renders selectable HTML buttons based on these configurations and then returns the selected button's value (id) to the callback function with ...

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...