0

I have a settings.js file that only contains definitions :

export default {
  maintenanceMode: 'yeahhhhh',
  enableRegister: false,
}

In order to make these settings available from everywhere in my app with this.$maintenanceMode for example, I added this, which works perfectly, to my main.js :

 Vue.prototype.$maintenanceMode = globalSettings.maintenanceMode
 Vue.prototype.$enableRegister = globalSettings.enableRegister

But when I try to assign values dynamically like this in my main.js :

for (const [key, value] of Object.entries(globalSettings)) {
  Vue.prototype['$' + key] = globalSettings[value]
  })
}

or like this :

for (const [key, value] of Object.entries(globalSettings)) {
  Object.defineProperty(Vue.prototype, '$' + key, {
    value: globalSettings[value],
  })
}

this.$maintenanceMode is undefined...

Does anyone has already done something similar or can point me where is my error ?

bhd
  • 3
  • 1

1 Answers1

0

You don't have to do this:

 Vue.prototype.$maintenanceMode = globalSettings.maintenanceMode
 Vue.prototype.$enableRegister = globalSettings.enableRegister

Just import those constants from settings.js file wherever you need them:

import * as settings from './settings'

EDIT >>> You can always assign variables to 'window' object, in order to reach them globally: https://stackoverflow.com/questions/11148997/window-variablename#:~:text=When%20a%20global%20variable%20is,can%20direct%20set%20window%20variable.&text=so%20when%20you%20declare%20a,value%20as%20a%20property%20value.

but the way I suggested at first is widely accepted way of handling global constants in JavaScript

JozeV
  • 616
  • 3
  • 14
  • 27
  • You are right but my primary goal was to only import it once for the entire app because their values will accessed from a lot of different places. The main problem is why my loop isn't working. – bhd Nov 16 '20 at 12:14