Access variables of a custom Vue plugin in single file components
Yesterday I came across the question “How to access variables declared in a custom Vue js plugin inside Components?” on Stack Overflow, and I decided to work out an answer for OP — and see what else could I add to make it somewhat useful.
In this article, I lead you through the basics of creating such a Vue plugin — from the beginning to the very end.
Problem statement
So the question was about creating a plugin’s data that can be accessed from ANY Single File Components and it gives back a constant value.
The Vue documentation has a pretty straightforward but not extensive explanation about how to write custom plugins & add it to the Vue instance.
Solution
Let’s create a project in terminal (assuming that you have Vue CLI installed and work on a Mac):
$ vue create custom-plugin
During installation chose the settings that you prefer. After installation enter the src folder under the project’s folder, create a folder for plugins (and enter that), create the file constants.js:
$ cd custom-plugin/src
src $ mkdir plugins
src $ cd plugins && touch constants.js
plugins $
Now open the /src/plugins/constants.js with your favorite text editor, and start the plugin as the documentation says:
A Vue.js plugin should expose an install method.
// /src/plugins/constants.jsexport default {
install(Vue) {}
}
You have to pass in Vue as a parameter, so you can work with it in your plugin. The second parameter would be options, but we won’t need that for this simple plugin. (With the options you could pass in parameters just before you initialize the Vue app.) Now we have the install method for our plugin. Let’s add functionality to it: our goal is to have a plugin that provides us with some constant values, that can be accessed from any component in the app. For that, a plugin that adds an instance method seems the best solution (we could also add global method(s), directives, mixins).
Write the function that returns the value:
// /src/plugins/constants.jsexport default {
install(Vue) {
Vue.prototype.$constants = function() {
return {
"VERSION": "1.0.1",
}
}
}
}
The code above will create an instance method that can be accessed in all of the app’s components be this.$constants() (or just {{ $constants() }} in the template parts). Yes, it will be accessible, but first, we have to add it to the Vue instance. You can do this by going to the /src/main.js, and edit it:
// /src/main.jsimport Vue from 'vue'
import App from './App.vue'
import Constants from './plugins/constants' // import the pluginVue.config.productionTip = falseVue.use(Constants) // tell Vue to use the pluginnew Vue({
render: h => h(App),
}).$mount('#app')
That was it. Now, if you want to see the result of your work, just go to /src/App.vue, and modify your template a bit:
// /src/App.vue - only showing the <template> part<template>
<div id="app">
{{ $constants() }} <!-- call the plugin in the template -->
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
After saving this modification, and starting the app in the terminal with
src $ npm run serve
you can see the object that you set in your /src/plugins/constants.js plugin.
Very nice, isn’t it?
Going a bit further
But this plugin only provides one value. I would like to create a more versatile plugin, that stores more constant values and I would like to be able to request only the values I need at certain points.
You could say that in the templates I could get it by
{{ $constants()["VERSION"] }}
True. I could get one value like that. But I would like to get one, two, three… or all values with one request.
So, let’s return to our plugin, /src/plugins/constants.js, and modify it:
// /src/plugins/constants.jsexport default {
install(Vue) {
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);
};
}
}
You can see that
- Now the function accepts arguments
- The object is replaced by an array of arrays
- The returned value takes into consideration the arguments
- The returned value is an object with only those key-value pairs that I specified in the arguments
Let’s see, how it works in the template:
// /src/App.vue<template>
<div id="app">
GET ALL CONSTANTS: {{ $constants() }}<br />
GET VERSION, RELEASE: {{ $constants("VERSION", "RELEASE") }}<br />
GET VERSION: {{ $constants("VERSION") }}<br />
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
Even nicer. If you omit the arguments — you get the whole object back.
And this is how you can add custom values accessible in every component in Vue 2.6.11, via a custom plugin.
If you have questions, comments, don’t hesitate to write here.