0

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();    
  }
};
1
  • 1
    I've never seen this requirement before, it gets tricky if you want to preserve the lifecycle hooks of Vue.js. Have you tried to register your component dynamically after your data has loaded? See: Vue API Vue.Component Commented Feb 10, 2019 at 18:11

1 Answer 1

1

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)
})
Sign up to request clarification or add additional context in comments.

1 Comment

Oh I did add a timestamp after the path to the json file to prevent caching. I omitted that in the code example for simplicity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.