I have tried to find the common best practice for this issue but I seem to be looking in the wrong places. What's the best practice to store content such as country codes (or any other static content, e.g. an array of categories etc.) in a vue.js app? It would be awkward to save that in my .env file as an environment variable and it isn't really another config variable either.
Should I just store it in Vuex even though this is immutable data and won't be changed by the user or app ever? Or should I just create my own js file and import it whereever I need it? In AngularJS I just put it in a HelperService as a function and that was it...
function getCountryArray() {
var countries = {
'AF': 'Afghanistan',
'AX': 'Åland Islands',
'AL': 'Albania',
'DZ': 'Algeria',
'AS': 'American Samoa',
'AD': 'Andorra',
'AO': 'Angola',
'AI': 'Anguilla',
'AQ': 'Antarctica',
'AG': 'Antigua and Barbuda',
'AR': 'Argentina'
...
You can make any property / function accessible on every vue instance (component) using Vue.prototype
.
Vue.prototype.getCountries = {
'AF': 'Afghanistan',
'AX': 'Åland Islands',
'AL': 'Albania',
'DZ': 'Algeria',
'AS': 'American Samoa'
};
Vue.component('test', {
template: `<div>{{ getCountries }}</div>`,
created() {
console.log('countries ->', this.getCountries);
}
})
new Vue({
el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<test />
</div>
Another alternative would be defining a global mixin and will work the same way.
Vue.mixin({
data() {
return {
get getCountries () {
return {
'AF': 'Afghanistan',
'AX': 'Åland Islands',
'AL': 'Albania',
'DZ': 'Algeria',
'AS': 'American Samoa'
};
}
}
})
Personal Preference
I prefer to have it on a .js (notice you also can import mixins to only use it in specific components - Vue Mixins) file and import it only in the components that will be used, to not overload all components with values not required.