0

I have created a custom Vue js plugin to store global variables like so:

Constants.js file:

import Vue from 'vue'
export default {

    install(Vue){

        Vue.Constants = {
            VERSION: '1.0.1'
        }
    }
}

Here is my main.js file:

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

Vue.use(Constants);

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

But when I tried accessing this constant in my App.vue it says undefined:


{{ Vue.Constants.VERSION }}  // Not working
{{ Constants.VERSION }} // Not working

I even tried importing Vue in App.vue like so:

<script>
import Vue from 'vue'

// Rest of the code

<script>

Please suggest, There are article on how to create and install custom plugin but I couldn't find how to access it in Vue components.

1 Answer 1

2

You need to tweak your code a little:

Constants.js file:

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

You have to add it to Vue.prototype not just Vue. Also, it's a convention to prefix the plugin with $ and lower-case it ($constants and not Constants).

This returns a function - so you have to call it like a function:

App.js or any other SFC:

{{ $constants().VERSION }} // expected: 1.0.1

SUGGESTION

If you just updated your plugin a bit, then it could really be 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);
    };
  }
}

If you try it out, then it's quite versatile:

App.js or any other SFC:

{{ $constants() }} // expected: { "VERSION": "1.0.1", "RELEASE": "05/08/20", "RELEASED BY": "I've released it." }
{{ $constants("VERSION", "RELEASE") }} // expected: { "VERSION": "1.0.1", "RELEASE": "05/08/20" }
{{ $constants("VERSION") }} // expected: { "VERSION": "1.0.1" }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.