In my Vuejs code, I am utilizing the plugins feature to define a global shared variable.
Vue.use(shared)
The shared
variable is defined as follows:-
export const shared = {
config: getAppConfig()
}
shared.install = function() {
Object.defineProperty(Vue.prototype, '$shared', {
get() {
return shared
}
})
}
function getAppConfig() {
var api = getAPIURL()
return axios.get("https://url/get_config")
.then(response => {
return response.data
}
}
However, when I try to access this variable in my component using this.$shared.config
, it returns undefined
.
After investigating and debugging, I realized that my component code is executed before the plugin has had time to populate this.$shared.config
.
Since I am new to JavaScript and Vuejs, I found out that this error could be due to axios being asynchronous. To address this, I attempted to return a promise and use await:
function getAppConfig() {
var api = getAPIURL()
return axios.get("https://url/get_config")
}
But, when trying to use await shared.config
inside my shared.install
function, I encountered an error:
Syntax Error: await is a reserved word
.
As a newcomer, it seems like I am making a fundamental mistake on how to make this code synchronous. What would be the correct approach to resolve this issue?