在组件加载之前初始化Vue.prototype

时间:2020-03-14 23:26:55

标签: javascript vue.js promise

我的代码使用Vuejs中的插件功能来定义全局共享变量。

Vue.use(shared)

shared定义为:-

export const shared = {
  config: getAppConfig()
}
shared.install = function() {
  Object.defineProperty(Vue.prototype, '$shared', {
    get() {
      return shared
    }
  })
}

function getAppConfig() {
  var api = getAPIURL()
  return axios.get("https://url/get_config")
  .then(response => {
    return response.data
  }
}

我的问题是,在我的组件中,如果我使用此变量this.$shared.config,则会得到undefined

在控制台窗口和调试语句中,我的组件代码在插件有时间进入this.$shared.config之前执行。

我是javascript + Vuejs的新手,但是当我研究此错误时,它与axios异步相关,因此我决定返回promise并使用await。

function getAppConfig() {
  var api = getAPIURL()
  return axios.get("https://url/get_config")
}

但是,当我使用shared.install函数时,我尝试这样做:-

shared.install = function() {
  let config = await shared.config

我收到错误消息:Syntax Error: await is a reserved word

由于我是新手,因此我在使代码同步方面似乎犯了一个基本错误。解决此问题的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

Vue不专门支持异步初始化的插件。

如果组件将在Vue.use(shared)之后立即实例化,则$shared将不可用。应该存在可链接的诺言,例如:

install() {
  Vue.sharedPromise = getAppConfig();
  Vue.sharedPromise.then(config => {
    Vue.prototype.$shared = config
  });
}

Vue.use(shared);
Vue.sharedPromise.then(() => {
  // $shared is available, mount app
});

由于实际上没有必要将异步操作推送到插件,因此可以将其保留在外部:

install(Vue, { config }) {
  Vue.prototype.$shared = config;
}

getAppConfig().then(config => {
  Vue.use(shared, { config });
  // $shared is available, mount app
});