Syffys
Syffys

Reputation: 610

Vue.js or Nuxt.js centralized app configuration

How can I load my static data in a single location within a nuxt/vue app?

Ideally I would have a JSON file holding all this data which would get loaded into vuex and would be accessible anywhere...

I've been suggested 2 options, but I don't find them clean...

Import the data from that file anywhere you need it (e.g. import { API_URL } from 'path/to/constants' ).

Upvotes: 1

Views: 2632

Answers (2)

Sudhir K Gupta
Sudhir K Gupta

Reputation: 65

I found one easiest way to set configs (json) file and and use in any component.

Steps -

  1. Create setting.json file in root directory.
  2. in middleware, create a file settings.js (or keep any name) and paste this code
    import settings from '../settings.json'
    export default function ({ store, route, redirect, req}) {
        process.env = settings
    }

3 in nuxt.config.js - add settings in

     router: {
            middleware: ['users', 'settings']
      },

uses - In any component or page -

data(){
      return {
            settings: process.env
      }
},

Now you can use settings anywhere in component.

Upvotes: 0

Syffys
Syffys

Reputation: 610

I've found an elegant solution using vue prototype

Hence with Nuxt.js

1) Create a plugin at ~/plugins/globals.js

import Vue from 'vue'
import globals from '~/globals.json'
import _get from 'lodash/get'

Vue.prototype.$g = (key) => {
  let val = _get(globals, key, '')
  if (!val) console.warn(key, ' is empty in $g')
  return val || key
}

2) Create your json file at ~/global.json

{
  "website_url": "https://www.company.com",
  "social": {
    "facebook": {
      "url": "https://www.facebook.com/company"
    },
    "twitter": {
      "url": "https://www.twitter.com/company"
    }
  }
}

3) Use these in every .vue file

<template>
  <div>
    <p>URL: {{ $g('website_url') }}</p>
    <p>Facebook: {{ fburl }}</p>
    <p><a :href="$g('social.twitter.url')">twitter</a></p>
  </div>
</template>
<script>
export default {
  data () {
    return {
      fburl: this.$g('social.facebook.url')
    }
  }
}
</script>

Upvotes: 6

Related Questions