0👍
Step 1: Create the configuration file
Create a new JSON file (e.g., config.json) that contains the configuration settings you want to use in your Vue.js app:
{
"apiBaseUrl": "https://api.example.com",
"apiKey": "your_api_key_here",
"enableFeatureX": true,
"maxItemsPerPage": 10
}
Step 2: Import the configuration file in your Vue app
In your Vue app’s entry point (e.g., main.js), import the configuration file using an HTTP request or a build tool like Webpack.
Example using Axios (ensure you have Axios installed):
import Vue from 'vue';
import App from './App.vue';
import axios from 'axios';
axios.get('/path/to/config.json')
.then(response => {
Vue.prototype.$config = response.data;
new Vue({
render: h => h(App),
}).$mount('#app');
})
.catch(error => {
console.error('Error loading config:', error);
});
Step 3: Use the configuration settings in your Vue components
Now that you’ve loaded the configuration settings into Vue’s prototype, you can access them in your Vue components using this.$config.
For example, in any of your Vue components:
<template>
<div>
<p>API Base URL: {{ $config.apiBaseUrl }}</p>
<p>API Key: {{ $config.apiKey }}</p>
<p v-if="$config.enableFeatureX">Feature X is enabled.</p>
<p>Max Items Per Page: {{ $config.maxItemsPerPage }}</p>
</div>
</template>
<script>
export default {
mounted() {
console.log('API Base URL:', this.$config.apiBaseUrl);
console.log('API Key:', this.$config.apiKey);
},
};
</script>
Source:stackexchange.com