How to get the value of an asynchronous request in main.js during initialization of a single file component

in the static directory, there is a configuration file that can be read dynamically after packaging. So I wrote this in main.js :

// 
axios.get("static/serverconfig.json").then((result) => {
  Vue.prototype.mainHostUrl = result.data.mainHostUrl
}).catch((error) => {
  console.log(error)
})

after mainHostUrl is mounted on the prototype, it can be accessed directly in the vue single file component (there is no need to mount it on data ).

however, contrary to one"s wishes, the value cannot be obtained in the created hook function

    console.log("url", this.mainHostUrl) // undefined

I meant to get mainHostUrl during page initialization, and then request data.

guessing is related to hook function and axios asynchronism, but because two files are involved, you can"t use promise . Please give us some advice!

Mar.16,2021

you can just put the code initializing vue in this callback.


write a self-calling function to change Synchronize asynchronously with await,


to instantiate the vue in main.js and start it wrapped in the async function to ok
https://www.jianshu.com/p/1d0.

.
Menu