【问题标题】:Vuejs constants from backend API来自后端 API 的 Vuejs 常量
【发布时间】:2017-07-07 16:15:27
【问题描述】:

我的后端有一个 API

api/v1/constants

在请求时返回所有应用程序常量。我想在加载我的 Vuejs 应用程序时调用此 API,并在某处设置这些常量,以便每个 vuejs 组件都可以导入这些常量并使用它们。

我可以在我的根组件中调用此 API,并在需要时将常量作为道具传递。但它正在将 prop 传递给嵌套组件。

例如

组件 A 将常量传递给组件 B,

组件 B 将常量传递给组件 C,

等等……

如果有人有更好的方法来管理这个,请推荐。

【问题讨论】:

  • 我会看看vuex
  • 感谢您的快速回复。我如何确保在屏幕上呈现任何其他组件之前加载常量。

标签: vue.js vuejs2


【解决方案1】:
Vue.prototype.$constants = <your constants>

可以在 Vue 或组件中的任何地方使用

this.$constants.<some constant>

【讨论】:

  • 看起来不错。 @Bert 我如何确保在渲染任何其他组件之前将常量添加到 Vue 原型中。
  • @Munish 在检索到常量之前不要初始化 Vue。就像在 promise 回调中初始化 Vue。
  • 我做了以下,很好Vue.http.get('/getConstants').then(res =&gt; { Vue.prototype.$constants = res.body.data; new Vue({ el: '#app' }); });
猜你喜欢
  • 2021-04-01
  • 2020-08-28
  • 2019-02-04
  • 2017-02-03
  • 2020-01-01
  • 2022-10-20
  • 2018-03-19
  • 2016-11-13
  • 1970-01-01
相关资源
最近更新 更多