I have to call an API (json-server) to retrieve data in order to populate my dropdowns within my Vue application. Instead of hard-coding within the app, I want to create an external configuration file where I can put any links and eventually put server details for deployment. Currently, I have this but for some reason when I reference the Key in my vue component, it says it undefined. I'm not sure where I'm going wrong.
/public/config.json
{
"API_URL": "localhost:3000"
}
Here is the relevant parts of the main.js file:
/main.js
fetch(process.env.BASE_URL+ "config.json")
.then((json) => {
json().then((config) => {
Vue.prototype.$config = config
new Vue({
router,
store,
render: (h) => h(App)
}).$mount("#app")
})
})
In my Vue component, I'm trying to reference it like this, but it is showing up as undefined.
<script>
export default {
mounted() {
fetch(this.$config.API_URL)
.then(res => res.json())
.then(data => this.mailboxes = data)
.catch(err => console.log(err.message))
}
}
</script>
If there is another way to go about this please let me know.
.envfile is the solution, just make sure that he is added in your .gitignore, for more detais check the officiel doc