Reputation: 131
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.
Upvotes: 2
Views: 847
Reputation: 37753
If you want the app build once and use same bundle on multiple servers with different configuration, this is right way to do it. ENV variables suggested in comments wont work as the values are "baked in" to the bundle...
However you are using fetch
in a wrong way. fetch
returns response which you are trying to call instead of calling response.json()
fetch(process.env.BASE_URL+ "config.json")
.then((response) => response.json())
.then((config) => {
Vue.prototype.$config = config
new Vue({
router,
store,
render: (h) => h(App)
}).$mount("#app")
})
Upvotes: 2