Randy Hall
Randy Hall

Reputation: 8137

Initialize vue after static data loaded

I have data that does not need a live binding and comes from a remote source. This is a JSON file generated by the server from some admin, and may be updated occasionally.

I have a Vue instance I want use that data in as a custom option to avoid unnecessary reactivity binding.

I cannot import into the .vue file itself in the build as it won't be built every time the data changes on the server.

If I'm loading each file (the store.json and main.js) I have a race condition here where the data might not yet be loaded when the main.js is loaded, and therefore my custom option would be empty.

Is there a Vue pattern for not initializing until some data is present?

Tried:

export default {
  store: "", 
  mounted(){
    httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function(){
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            this.store = JSON.parse(httpRequest.responseText);
            console.log(this.store) //shows the expected return, but obviously no update to the page
        }
    }
    httpRequest.open("GET", "/store.json", true);
    httpRequest.send();    
  }
};

Upvotes: 0

Views: 457

Answers (1)

Fabian Hijlkema
Fabian Hijlkema

Reputation: 391

I’ve had a similar case once with the need to adjust some presets without rebuilding the project every time. I ended up moving the Vue object that rendered the app inside an async Axios function. Of course it affects loading time, since it waits for the JSON file to be loaded, in my case this was less important. This is a summary of such a setup.

axios.get('./config.json')
.then(function(response) {
    let config = response.data
    //commit data to vuex store for example

    new Vue({
        store,
        render: h => h(App)
    }).$mount('#app')
})
.catch(function(error) {
    console.log(error)
})

Upvotes: 1

Related Questions