1

I have a js file named Constant.js which contains all API names.

//Constant.js
export default {
    api1: 'api1',
    api2: 'api2',
    ...
    ...
    ...
}

How do I use this file without importing it in every Vue components there are in my app?

yareyaredaze
  • 85
  • 2
  • 10
  • Add your `constant` object to the window object and use it everywhere – Prithwee Das Jul 08 '21 at 18:12
  • 3
    Just found a likely duplicate: [What is the best way to declare global variable in Vue.js?](https://stackoverflow.com/questions/37367588/what-is-the-best-way-to-declare-global-variable-in-vue-js), specifically [this answer](https://stackoverflow.com/questions/37367588/what-is-the-best-way-to-declare-global-variable-in-vue-js/48895742#48895742) which is essentially what I wrote below. – zcoop98 Jul 08 '21 at 19:30

1 Answers1

2

While adding the data directly to your Window object is definitely an option, the most "Vueish" way to do this is to import your data object in main.js (or equivalent) and create an instance property by adding it to the Vue prototype:

main.js

import global_constants from `./Constants`;

... // Other imports, Vue.use, Vue.component, etc.

Vue.prototype.$global_constants = global_constants; // Adds object to Vue's prototype

new Vue({
... // Create Vue instance with desired config etc.
});

This will make that data accessible by all child components attached to that instance through this.$global_constants.

The name itself is arbitrary and can be anything you'd like, and the $ at the start is Vue's naming convention for all instance properties.

tony19
  • 125,647
  • 18
  • 229
  • 307
zcoop98
  • 2,590
  • 1
  • 18
  • 31