Why use a static config file in Vue
If the config is inside Vue, the value in the config needs to be defined before the Vue compile. This means it’s not possible to change the config after the Vue site is deployed to a web server. To flexibly update config values, it can be helpful to have a static config file outside of Vue components.
How to set up a static config file in Vue
1.Create config.json file in the public folder
{ "title": "Static Config!" }
2. Load config.json file before mounting the Vue app at main.js. The config value can be added to
app.config.globalProperties.YourVariableName
import './assets/main.css' import { createApp } from 'vue' import App from './App.vue' const app = createApp(App); fetch('/config.json?' + Date.now()) .then(response => response.json()) .then(config => { app.config.globalProperties.pageTitle = config.title; app.mount('#app'); });
3. Read YourVariableName globally in Vue templates or scripts.
<script> export default { data() { return { pageTitle: this.pageTitle, } } } </script> <template> <div class="greetings"> <h2>Config called in template: {{ this.pageTitle }}</h2> <br> <h2>Config called in script: {{ pageTitle }}</h2> </div> </template>
Sample Code: rocker8942/vue-static-config (github.com)