How can Components access variables declared in a custom Vue.js plugin?

I had developed a unique Vue js plugin to manage global variables as shown below:

CustomConstants.js file:

import Vue from 'vue'
export default {

    install(Vue){

        Vue.CustomConstants = {
            APP_VERSION: '2.1.0'
        }
    }
}

This is my app.js file:

import Vue from 'vue';
import App from './App';
import CustomConstants from './plugins/CustomConstants'

Vue.use(CustomConstants);

new Vue({
    render: h => h(App)
}).$mount('#app')

However, I encountered an issue when trying to access this constant in my App.vue component, it was returning undefined:


{{ Vue.CustomConstants.APP_VERSION }}  // Not showing
{{ CustomConstants.APP_VERSION }} // Not displaying

I attempted importing Vue directly into App.vue like this:

<script>
import Vue from 'vue'

// Remaining code here

<script>

If anyone has suggestions, please share. While there are resources on creating and installing custom plugins, accessing them in Vue components seems less documented.

Answer №1

To improve your code, make the following adjustments:

constants.js file:

export default {
  install(Vue, options) {
    Vue.prototype.$constants = () => {
      return {
        VERSION: '1.0.1'
      };
    };
  }
}

Make sure to add it to Vue.prototype rather than just Vue. Also, follow the convention of prefixing the plugin with a $ and using lowercase letters ($constants instead of Constants).

Since this returns a function, you need to call it as a function:

App.js or any other single file component:

{{ $constants().VERSION }} // Expected result: 1.0.1

RECOMMENDATION

If you tweak your plugin slightly, it could serve as a "constant-store":

constants.js file:

export default {
  install(Vue, options) {
    Vue.prototype.$constants = function(...args) {
      const constants = [
        [
          "VERSION",
          "1.0.1"
        ],
        [
          "RELEASE",
          "05/08/20"
        ],
        [
          "RELEASED BY",
          "I've released it."
        ]
      ]
      return args.length
        ? Object.fromEntries(constants.filter(([key]) => args.includes(key)))
        : Object.fromEntries(constants);
    };
  }
}

Once implemented, the versatility becomes evident:

App.js or any other single file component:

{{ $constants() }} // Expected result: { "VERSION": "1.0.1", "RELEASE": "05/08/20", "RELEASED BY": "I've released it." }
{{ $constants("VERSION", "RELEASE") }} // Expected result: { "VERSION": "1.0.1", "RELEASE": "05/08/20" }
{{ $constants("VERSION") }} // Expected result: { "VERSION": "1.0.1" }

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

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

Utilize html5 to drag and drop numerous items effortlessly

Recently, I created a basic HTML5 drag and drop feature using JavaScript. However, I encountered an issue. function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

The file type stored in Firebase storage is identified as 'octet-stream' rather than the expected 'png/jpg' format

I am experiencing an issue with uploading images to Firebase storage. After uploading them, I notice that they are labeled as application/octet-stream instead of the expected types like image/jpeg or image/png. Below is the code snippet I am using: <in ...

In JavaScript, implement event listeners exclusively on the main container and its immediate child elements

Is there a way to target just the main container and its second child elements for an event? Specifically, targeting id="container" and all elements with class="secondChild" Currently, I have a listener attached to all elements inside ...

Leveraging Node.js to establish a connection between two pug files

Recently, I decided to delve into the world of pug and JavaScript. However, I seem to be facing a small issue that I can't quite figure out on my own. My project involves creating multiple .pug files with various text content that I can navigate betwe ...

Extracting Querystring Value in C#

When using the code below to set the iframe src with JavaScript, everything works as expected. However, in the C# code behind, I am receiving the query string in a format like this: id=Y&amp%3bcust_id=100&amp%3. Is there a way to simplify this? v ...

Develop search bar button and file directory components

Within this application, there is a search engine designed to scan through the file tree for specific content. The goal is that upon entering a search query and clicking the Search button, the file tree will filter and display the relevant information. Cu ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...

Enhance the attributes of a collection of objects using values from a different array

Looking for a way to enhance a set of objects with properties sourced from another array? I have two arrays at hand. The first one contains a series of objects, while the second one consists of integers. My goal is to attribute a new property to each objec ...

Transforming Child_process.spawn's "Promise" syntax into "async/await" syntax.---Here's how you can convert the syntax of Child_process.spawn from using

Trying to wrap my head around the async/await syntax, I have come accross a code snippet that intrigued me. The following is the Promise-based version of the code: function callToolsPromise(req) { return new Promise((resolve, reject) => { l ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

`Scrolling through a horizontal menu with no scrollbar present`

Is there a way to create a horizontal menu that can scroll left or right without the scrollbar? I'm looking for a solution like adding on-screen arrow buttons or implementing mouseover functionality. What would be the best approach? div.scrollmenu ...

Generating text upon clicking by utilizing vue apex charts dataPointIndex

Is there a way to populate a text area on click from an Apex chart? The code pen provided below demonstrates clicking on the bar and generating an alert with the value from the chart. Instead of displaying this value in an alert, I am looking to place it o ...

Troubleshooting a Messaging Error between Background and Another Script

Attempting to transfer selected text from the current page to an HTML page using message passing: content script to background script, then background script to the HTML page. However, encountering errors if the HTML page is not already open, and even gett ...

Troubleshooting three.js exceeding 2-minute load times and crashing issues

I am currently in the process of developing a 3D game and have encountered an issue with the localhost GET request taking longer than expected. After around 15-45 seconds, the canvas turns white and I receive a warning in the console indicating that the We ...

The repetition of the react nodejs page load occurs when the get method is utilized

I've successfully set up a page and function for loading the customer list. However, I'm facing an issue where adding the get method to my code results in it being called every time information is received from the URL and the page is rendered. i ...

Exploring the Differences between Slim Framework's Currying and Dependency Injection

Frameworks like Angular allow for injecting services and controllers into each other, as shown in the code snippet below: App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { ...

Troubleshooting: Issues with Integrating Javascript and CSS into

I'm still new to this platform, so please correct me if I make any mistakes. My goal is to create a "task table" that allows users to edit existing tasks and add new ones. Thanks to the base template provided by Ash Blue, I've managed to program ...