0

Could someone tell me what is wrong with this setup, where I want to load a config.json file before the vue app is created and access the config in the components with this.$root.config. There is no root config element I can access? Missing something? Thanks for your help! The config.json file is correctly loaded, can log the config to the console. But it is not added to the root properties from Vue?

fetch('/config.json')
.then(res => res.json())
.then(config => {
    createApp(App, {
        data() {
            return config
        },
        created() {
            console.log(this.$root.config);
        }
    }).use(store).use(router).use(i18n).mount('#app');
});

2 Answers 2

1

What you place in data won't be found in $root but, as Abdelillah pointed out, in $root.$data. Since App is the root component, though, you can just use this.config. In any subcomponent, you'd have to use this.$root.$data.config.

But Vue 3 provides a cleaner alternative to provide data to any component in your app: config.globalProperties.

Example:

const app = Vue.createApp({});
app.component('test', {
  mounted() {
    console.log(this.config);
  }
});  

Promise.resolve({
  foo: 'bar'
}).then(config => {
  app.config.globalProperties.config = config;
  app.mount('#app');
});
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
  <test />
</div>

As you can see, logging <test>'s .config outputs the globalProperty.config set on the app, and it's going to be the same for any component in the app.

If you want to provide data to any descendants of current component (no matter how deep, skipping intermediary parents), you could use provide/inject. While I find this particularly useful for providing some data to all the children of a particular component (and not to the rest of the app's components), it can obviously be used on the root component, which would make the provide available cross-app via inject wherever you need it.

Sign up to request clarification or add additional context in comments.

Comments

0

there is no property called config on your data, what you are doing is simply returning the JSON object you imported, you should be doing:

fetch('/config.json')
.then(res => res.json())
.then(config => {
    createApp(App, {
        data() {
            return {
             // config: config
              config 
            }
        },
        created() {
            console.log(this.$root.$data.config);
            // or console.log(this.config);
        }
    }).use(store).use(router).use(i18n).mount('#app');
});

Comments

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.