Employing global variables in JavaScript files with Vue3

In my Vue3 project, I have defined global variables like this:

 app.config.globalproperties.$locale = locale

A composable function has been created to dynamically retrieve these global variables:

import { getCurrentInstance ) from 'vue'
export function useGlobals(type) {
  const app = getCurrentInstance()
  const global = app.appContext.config.globalProperties[`$${type}`]
  return { global }
}

These composable functions are then imported and used in Vue components:

import { useGlobals } from '../path'
const { global } = useGlobals('locale')

This allows the global variables to be accessed. However, an issue arises when trying to import the composable function in JavaScript files, as the appContext is undefined there.

My question is, is there a way to access global variables or the appContext in JavaScript files?

Answer №1

After receiving a valuable suggestion from @tao (by the way, it's not possible to retrieve appContext from the app itself, but that sparked an idea :)), the issue has been resolved.

I have added another export in main.js, following the creation of the app, containing all global properties:

const globals = app.config.globalProperties
export { globals }

Alternatively, as suggested by @tao, it can be exported as a function:

export const useGlobals = () => app.config.globalProperties

Now, we are able to import globals into any js file and utilize them like this:

import { globals } from '../path/to/main.js'
globals.$locale

Alternatively, using a function:

import { useGlobals } from '../path/to/main.js'
const { $locale } = useGlobals()

Answer №2

After trying the solution recommended by @nikola-pavicevic, I encountered a problem with infinite recursion. Each time globals was imported, it triggered a complete run-through of main.js, resulting in the app being initialized and mounted again. While the app seemed to function correctly in production, the Jest unit tests revealed numerous issues caused by this recursive behavior.

To address this issue, I devised a workaround by creating a separate file named GlobalVariableHolder.js with the following content:

const GlobalVariables = {};
export default GlobalVariables;

Subsequently, within main.js, I could import it using:

import GlobalVariables from "./GlobalVariableHolder";

Next, I assigned the variables as follows:

// Be sure to assign the variables to app.config.globalProperties before running this line.
GlobalVariables.variables = app.config.globalProperties;

Once done, when needing these variables in another JS file, the import statement remains unchanged:

import GlobalVariables from "./GlobalVariableHolder";

This approach allows access to all items from

app.config.globalProperties</code like so:</p>
<pre class="lang-js"><code>GlobalVariables.variables.$thisIsAMethod(parameter);

By employing this method, importing GlobalVariableHolder no longer results in setting up a new Vue instance every time.

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

What is the best way to verify the number of values stored within a variable in JavaScript?

My goal is to calculate the sum of 6 values by inputting them into a single field using a button. To achieve this, I am seeking knowledge on how to determine the number of values contained within a variable. This will allow me to implement an "if" conditi ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Tips for creating a dynamic component with v-for and utilizing dynamic slots

I am facing an issue with a child component that utilizes v-for. My goal is to allow the parent component to dictate how each item within the v-for loop is displayed by passing down a slot or similar mechanism. The challenge lies in the fact that the paren ...

What are the reasons for the dynamic exclusion of an element in Angular?

Can someone help me figure out why my data is not being added dynamically using ng-repeat? I have entered the "name" which should be added to the data, but it is not displaying in the UI. You can see the issue in this demo app.controller("studentcntr", ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Attempting to create an animated carousel slider

I've been working on creating a carousel animation that displays 3 images, slides them to the left, and brings in new ones. I'm feeling a bit stuck and could use some assistance. Check out my work so far on this fiddle link: http://jsfiddle.net/ ...

Blank Vue Page Generated by Laravel Mix

While attempting to run npm run dev or npm run production, I encountered an error stating that the Vue file did not have loaders defined. To resolve this issue, I turned to this helpful resource: Compillation problem of extensions in vuejs I made use o ...

Tips for avoiding the need to reload a single page application when selecting items in the navigation bar

I am in the process of creating a simple Single Page Application (SPA) which includes a carousel section, an about us section, some forms, and a team section. I have a straightforward question: How can I prevent the page from reloading when clicking on nav ...

Exploring the process of reading a file from a specified file path within a text area using jQuery

I am looking for a way to dynamically read a file based on its path, and then display the contents of that file in a text area. I have attempted to do this with the following code, but it is not working as expected. Here is the code snippet: goog ...

Having difficulty converting a local variable into a global variable in JavaScript and Express

I am facing challenges trying to convert a local variable into a global variable while working with Express and Javascript. Below is my JavaScript code snippet: // Setting up Express and EJS const express = require("express"); const JSON = requi ...

Encountering a React JS error with Admin on Rest while making an API request

When making an API call (GET) with React.js using Admin on Rest, I encountered an issue. The server returns data when calling localhost:5001/cities, but there seems to be an error on the client side as indicated by the browser log: failure.js:18 Error: Th ...

ASP.NET - The Power of a Long Press

I am currently working on implementing a Long Press event in JavaScript on an ASPX page. Due to my limited experience with JavaScript, I am facing a few challenges. I found a similar question that was previously asked here. When running the code, I encoun ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

Utilize Express Node to display API information on HTML pages using Handlebars template

I'm seeking assistance in rendering data from an API to HTML using handlebars. I'm a bit puzzled on how to properly showcase the data on the webpage. Here's what I have so far: ROUTES FOLDER/FILE: const express = require('express&ap ...

Retrieve the identification of elements with dynamically generated ids

I've dynamically generated a set of elements using Handlebars, as shown below {{#floor as |room i|}} <div class="btn-group-toggle" data-toggle="buttons" > <label class="btn btn-secon ...

What is the best way to update $state in AngularJs when the user makes changes to the controller?

I am currently working on Angular UI Router and I want to refresh the current state by reloading it and rerunning all controllers for that state. Is there a way to reload the state with new data using $state.reload() and $stateParams? Here is an example ...

Theme not being rendered properly following the generation of a dynamic component in Angular

I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file a ...

The functionality of a jQuery click event may cease to work once a loader has been incorporated into a

Since implementing a loading feature in my Vue template, I have encountered issues with jQuery not functioning properly: var element = document.getElementById('vue-project') if (element !== null) { var getData = await axios.get('./dat ...

Phonegap app failing to run Ajax request properly

I have recently updated my Android app using phonegap build to the latest version, cli-5.2.0. Here is a snippet of my config: <preference name="phonegap-version" value="cli-5.2.0" /> Additionally, here is how my overall configuration looks like: & ...

The battle between Hover, Focus, and Blur modes intensifies

My goal is to implement 4 different effects on an element: When hovering over the element. When moving away from the element. When focusing on the element. When blurred. However, I'm encountering a conflict where when I focus on the element, the ...