Home > Mobile >  Get config value in vue file
Get config value in vue file

Time:11-19

possibly a very simple question: I need to get a configuration value from within an html block in a vue file.

I have this simple config.js

const env = process.env.NODE_ENV

const development = {
  images: {
    server: "http://localhost:4001",
  }
}

const production = {
  images: {
    server: "http://someimageserver.com",
  }
}

const config = {
  development,
  production,
}

module.exports = config[env]

And this simple vue.js

<template>
  <div>
      <img :src="`${config.images.server}/images/someimage.jpg`"/>
  </div>
</template>

At run time, the above throws

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'images')

What should I do to make this work ? Thanks in advance

Note: I can get configuration values from within the script block using, this works perfectly, for example

import config from "../../config"
...
var c = config.images.server

UPDATE: Using vue 3, one can easily achieve this by adding

import config from "../config"
app.config.globalProperties.$config = config

to the main.js file. From there on, $config can be used in templates and scripts across all files. Source: https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties

CodePudding user response:

In Vue, you need to initiate a variable and assign what you imported to it, and eventually return this variable. It looks like below:

Vue2:

import config from "../../config"

export default {
  data() {
    return {
      config: config
    }
  }
}

Vue3:

import config from "../../config"

export default {
  setup() {
    return {
      config
    }
  }
}

Then the url in the template should work fine.

-------------------------updates-----------------------

If you want to use config globally, you can register it as a Plugin.

Create plugin.js

import config from "../../config"

export const Config = {
  install(Vue, options) {
    Vue.prototype.$config = function() {
      return config
    }
  }
}

Then, in your main.js, add below code

import * as Plugins from '@/plugin.js'

Vue.use(Plugins.Config.install)

Then you can use $config within templetes like $route without any other import. Surely you can write other global functions in plugin.js and register each of them in main.js.

  • Related