What is the best way to incorporate global variables within Vue JS components?

I am currently working on creating a web-app using Vue JS. I have come across the concept of Single File components(.vue files) which seems like a great way to create components. However, I am looking to avoid using any node modules. That's when I discovered https://github.com/FranckFreiburger/http-vue-loader, which allows me to load .vue files directly from my html/js.

My goal is to display real-time data from a websocket into an html table that is located inside a component. I want to utilize the same websocket data for multiple components. To achieve this, I set up the websocket and a global variable outside the component (in app.js) to store the data. I then used this variable inside my component for real-time data updates. However, the html table is not updating despite receiving the data.

The concept is to establish a single websocket connection and share the data across multiple components.

As I am relatively new to the Vue framework, I appreciate any assistance in addressing this issue or suggestions for alternative approaches. Thank you.

index.html

<!DOCTYPE html>
<html>

<body>
  <div id="app">
        <div>
          <comp1></comp1>
          <comp1></comp1>
        </div>
  </div>

  <script src="js/vue.js"></script>
  <script src="js/httpVueLoader.js"></script>
  <script src="js/app.js"></script>
</body>

</html>

app.js

var global_data = [];
var ws = new WebSocket("ws://127.0.0.1:9012/ws");
ws.onmessage = msg => {
   global_data = JSON.parse(msg.data);
   console.log(global_data);
};

new Vue({
  el: "#app",
  components: {
    'comp1': httpVueLoader('js/component1.vue')
  },
  data: {

  }
});

component1.vue

<template>
  <div>
    <table id="tm_table" class="content-table">
      <thead>
        <th>Parameter</th>
        <th>Value</th>
      </thead>
      <tbody>
        <tr v-for="(parameter, id) in rt_data.params" :key="id">
          <td>{{parameter.param}}</td>
          <td>{{parameter.value}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
module.exports = {
  data() {
    return {
      rt_data: global_data,
    };
  }
};
</script>

<style>
</style>

Answer №1

If you want to avoid using Vuex, one approach is to store your global variables in the parent component and simply pass them down as props to child components. Another option is to utilize the browser's local storage to store data and retrieve it in components as needed. This method essentially functions as a way to establish global variables and has become quite popular in the development community.

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

Bootstrap modal with autocomplete feature

How can I display the last entered data by the user in a bootstrap modal? I attempted to use the HTML autocomplete="on" attribute but it did not work, similar to what is shown in this fiddle. After the user submits, on the subsequent attempt, it should pr ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

Retrieve data from HTML Form arrays using JavaScript

I have a situation in my forms where arrays are being sent back in the following format: <input class="checkbox-service" name="services['electricity']" type="checkbox"> <input class="checkbox-service" name="services['water'] ...

Dynamic display without AJAX

I need assistance with two drop-down lists where the second list's values should change based on the selection made in the first list. The current set up of the drop-down lists is as follows: <select name="first"> <option name="a" va ...

Resetting the countdown timer is triggered when moving to a new page

In my current project, I am developing a basic battle game in which two players choose their characters and engage in combat. The battles are structured into turns, with each new turn initiating on a fresh page and featuring a timer that counts down from ...

I am unable to access the properties of an undefined element, specifically the 'size' property in Next.js 13

I encountered a problem today while working with Next.js version 13.4 and backend integration. When using searchParams on the server side, I received an error message: "Cannot read properties of undefined (reading 'size')" while destructuring siz ...

Unable to choose anything beyond the initial <td> tag containing dynamic content

Struggling to implement an onclick delete function on dynamically selected elements, but consistently encountering the issue of only selecting the first element each time. // Function for deleting entries $("#timesheet").on('click', &ap ...

The validations continue to function properly even when HTML has been removed

In my form, I have implemented an "addmore" functionality that allows users to dynamically add a set of HTML input fields. Users can also remove the added rows if needed. While everything is functioning correctly, I am encountering an issue where validatio ...

Personalizing/Concealing Navigation Controls

Looking for a way to customize the Navigation in the Pagination Plugin; changing 'First, Prev, Page 1, Page 2, Next, Last' to 'Prev, Next, Page 1 of 2' The documentation suggests using show_first_last set to false to hide 'First/L ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

Error Message: Nodemon Node Error - Module 'C:Program FilesGit ode_modules odemonin odemon.js' Not Found

Currently diving into the world of NodeJS. Running a Windows 7 64 Bit setup. Node.js and NPM are up and running smoothly. Nodemon is also installed locally and globally. When trying to execute the command: "nodemon server.js" or simply "nodemon" An er ...

Access the value of a JavaScript global variable using Selenium in Python

I need to access a value from a global variable in JavaScript: clearInterval(countdownTimerTHx); var saniye_thx = 298 // <--- Variable here function secondPassedTHx() { https://i.sstatic.net/odIbh.png My goal is to retrieve the value " ...

The npm error message indicates that there is an issue with the transpileDependencies.map function

Every time I attempt to execute my program, this error pops up: https://i.stack.imgur.com/ANA0z.png Even after uninstalling and reinstalling node, the error persists. ...

Is it possible to iterate through HTML elements without relying on forEach()?

Currently working on my web-based system using Node.js and HTML. Are there any alternative ways to iterate through HTML elements without using forEach? I'm considering something like this (for example): <% for(var ctr=0; ctr<arrayname.length ...

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...

Unexpected appearance of a blue line in Material UI when the overflow attribute is included

For my React application, I've integrated Material-UI along with styled components. The strange thing is that when I use a Chrome browser to view the app, I encounter an issue that doesn't seem to happen in Firefox. The problem arises when I add ...

AngularJS users are experiencing issues with the "See More" feature not functioning as expected

One of my tasks involves dealing with a block of text that needs to be truncated using ellipsis. To achieve this, I am utilizing jquery dotdotdot. For more information on dotdotdot, please refer to the documentation. I have created a straightforward dire ...

Menu icon in Next.js/React/Tailwind not triggering close action when clicked again, causing responsiveness issue

Hey there, I'm relatively new to working with Next.js and React. Right now, I'm tackling the challenge of creating a responsive navbar that toggles open and closed when clicking on the hamburger icon (and should also close when clicked outside th ...