Where to store static content (e.g. country codes) in a vue.js app?
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.