如何在外部js文件中访问Vue.prototype?

时间:2020-09-09 01:52:30

标签: node.js vue.js

"vue": "^2.4.4"

我在main.js中定义了属性:

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

我在src / common中还有一个名为version.js的js文件

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---------------------")

我无法理解控制台日志: 原型1包含baseURL,但未定义baseURL 1。 原型2不包含baseURL,并且baseURL 2未定义。

如果我想在version.js中获取baseURL。我该怎么办?

1 个答案:

答案 0 :(得分:1)

第一个问题是只有.env前缀为VUE_APP_的属性才能将其放入捆绑文件中。

Environment Variables

请注意,只有NODE_ENVBASE_URL和以VUE_APP_开头的变量将通过webpack.DefinePlugin静态地嵌入到客户端包中。

将您的.env文件更改为

VUE_APP_API_ROOT=https://whatever/

第二,这正是Vue plugins的目的……

  1. 通过将某些Vue实例方法附加到Vue.prototype来添加它们。

您可以author your own plugin如此简单

// 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",
})

您只需要在创建根Vue实例之前确保已安装插件即可。