2
"vue": "^2.4.4"

I defined properties in main.js:

Object.defineProperties(Vue.prototype, {
  baseURL: {
    value: process.env.API_ROOT,
    writable: false
  }
});

I have another js file named version.js in src/common

import Vue from "vue";
let app = new Vue({
  el: "#app",
})
console.log("---------------------version start---------------------")
console.log("prototype 1:", Vue.prototype)
console.log("baseURL 1:", Vue.prototype.baseURL)
console.log("---------------------version end---------------------")

console.log("---------------------app start---------------------")
console.log("prototype 2:", app)
console.log("baseURL 2:", app.baseURL)
console.log("---------------------app end---------------------")

I can not understand the console log: prototype 1 contains the baseURL but baseURL 1 is undefined. prototype 2 didn't contains baseURL and baseURL 2 is undefined.

If I want to get the baseURL in version.js. what should I do?

1 Answer 1

2

First problem is that only .env properties prefixed with VUE_APP_ make it into your bundled files.

Environment Variables

Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin.

Change your .env file to

VUE_APP_API_ROOT=https://whatever/

Second, this is exactly what Vue plugins are for...

  1. Add some Vue instance methods by attaching them to Vue.prototype.

You can author your own plugin very simply like this

// base-url-plugin.js
export default {
  install: Vue => {
    Object.defineProperty(Vue.prototype, "baseURL", {
      value: process.env.VUE_APP_API_ROOT ?? "https://some-default/",
      writable: false
    })
  }
}
import Vue from "vue"
import baseUrlPlugin from "./path/to/base-url-plugin.js"

// install the plugin first
Vue.use(baseUrlPlugin)

// now create your root Vue instance
let app = new Vue({
  el: "#app",
})

You just need to ensure your plugin is installed before creating the root Vue instance.

Sign up to request clarification or add additional context in comments.

4 Comments

how to make sure my plugin is installed before creating the root Vue instance?
It's your code man, just make sure you run that Vue.use({...}) bit before let app = new Vue({...}). I've updated my answer to try and make it clearer
Is there any common place I can init ,just like java spring beans. and then I can use it all over the project.
I don't really understand your question. The code above is only in one place

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.