Set up Vue.prototype prior to the component loading

In my Vuejs code, I am utilizing the plugins feature to define a global shared variable.

Vue.use(shared)

The shared variable is defined as follows:-

export const shared = {
  config: getAppConfig()
}
shared.install = function() {
  Object.defineProperty(Vue.prototype, '$shared', {
    get() {
      return shared
    }
  })
}

function getAppConfig() {
  var api = getAPIURL()
  return axios.get("https://url/get_config")
  .then(response => {
    return response.data
  }
}

However, when I try to access this variable in my component using this.$shared.config, it returns undefined.

After investigating and debugging, I realized that my component code is executed before the plugin has had time to populate this.$shared.config.

Since I am new to JavaScript and Vuejs, I found out that this error could be due to axios being asynchronous. To address this, I attempted to return a promise and use await:

function getAppConfig() {
  var api = getAPIURL()
  return axios.get("https://url/get_config")
}

But, when trying to use await shared.config inside my shared.install function, I encountered an error:

Syntax Error: await is a reserved word
.

As a newcomer, it seems like I am making a fundamental mistake on how to make this code synchronous. What would be the correct approach to resolve this issue?

Answer №1

When using Vue, plugins that require asynchronous initialization are not directly supported.

If a component is created immediately after calling Vue.use(shared), the variable $shared may not be accessible. To handle this, you can create a promise chain like so:

install() {
  Vue.sharedPromise = getAppConfig();
  Vue.sharedPromise.then(config => {
    Vue.prototype.$shared = config
  });
}

and

Vue.use(shared);
Vue.sharedPromise.then(() => {
  // $shared is now available, continue with mounting the app
});

It's important to note that if an asynchronous operation doesn't need to be part of the plugin itself, it can be handled separately:

install(Vue, { config }) {
  Vue.prototype.$shared = config;
}

and

getAppConfig().then(config => {
  Vue.use(shared, { config });
  // $shared is now available, proceed with mounting the app
});

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

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Find out which way the user is scrolling in your React js application

I'm struggling to determine whether the scroll event is moving up or down, and I haven't been able to find a solution yet. import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; const Nav ...

Error receiving by React while updating an array with setState() in TypeScript

I am in search of a way to adjust a property of an item within an array by using the updater returned from setState. The function is passed down as props to the child, who then invokes it with their own index to update their status. const attemptToUpdate ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...

Only displaying the VUE slot when the content meets a certain criteria

I have encountered a situation where I have two routes rendering the same component but with different data from an API source. The component in question has a child component called <base-section> that utilizes a v-if directive to determine whether ...

How to eliminate undefined values from a dropdown selection in AngularJS

Blockquote When choosing a material from the column, the first option is showing as undefined. How can I remove undefined from the drop-down list? What changes need to be made in the HTML/JSON data for this to work properly? Blockquote var app = ang ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

Best Practices for Safely Storing the JWT Client Credentials Grant

Currently, I am working on a NodeJS Express Application that connects to an Auth Server using client credentials grant. After receiving the token from the Auth Server, I use it to access data from an API. I am seeking advice on the most effective way to s ...

Tips for extracting data from various select drop-down menus within a single webpage

As a newcomer to JQuery, I apologize if this question seems basic. I have a page with 20 categories, each offering a selection of products in a drop-down menu. The user will choose a product from each category, triggering an ajax call to retrieve the pric ...

What measures can be taken to minimize the number of API calls triggered by vue hot reload?

I recently began learning Vue and have started developing my initial project. Within my primary component, I've implemented a fetch request to a restricted API endpoint upon page load. However, with each code modification, the page undergoes a refres ...

Animating an image into a Vue.js div

Is it possible to create a dynamic image animation using Vue.js? I am looking to create an interactive "Add to Cart" experience where when a user clicks on the button, the product's image smoothly glides over to the shopping cart icon before fading a ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

Excessive wait times during the construction of a moderately sized application (over 2 minutes) using TypeScript and loaders like Vue-Loader and TS-Loader

I'm currently utilizing Nuxt 2 with TypeScript and the most up-to-date dependency versions available. Even though my app is of medium size, the compilation time seems excessively slow. Here are my PC specs: Ryzen 7 2700X (8 Cores/16 Threads) 16 GB D ...

Tips for translating an HTML webpage from Arabic to English

I have a bootstrap site with HTML pages but no backend functionality. How can I manually translate from Arabic to English, given that I already have the translations for all content and don't need to rely on translation tools? Is there a way to map Ar ...

Can someone help clear up this confusion with CSS?

Why is image 6.png selected, when all the images are direct descendants of the div shape? Thank you for your assistance, it's greatly appreciated. As far as I know, it should select all the divs because they are all direct descendants of the div #shap ...

Analyzing - Dynamically Tagging Method - Implementing direct call regulations- Erase enduring variables

https://i.sstatic.net/elGJz.jpg Hello there, I am currently utilizing a Direct call rule within DTM. When I click on a href link that opens in a new window, I want to remove or clear the eVars and events associated with the click. I have implemented custo ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

Tips for invoking a controller method in HTML code

Hello, I am completely new to AngularJS, HTML, JavaScript, and CSS. Please keep your explanations simple for beginners like me. I'm facing an issue where the function "updateFilterTerm" is not being called, causing the variable "filterTerm" to remain ...

Creating a Vue equation that utilizes props to dynamically assign a class

I am trying to dynamically apply a class to a data table based on the data being passed to it. Although I can successfully run the equation in the template, I'm having trouble figuring out how to do so within the bound class. Let me show you what my ...