在Vue.js中创建一个全局变量 [英] Creating a global variable in Vue.js
问题描述
在Vue.js 0.12中,很容易将一个变量从根组件一直传递给它的子节点:你只需在任何一个上使用 inherit:true
需要其父级数据的组件。
In Vue.js 0.12, it was easy enough to pass a variable from the root component all the way down to its children: you just use inherit: true
on any component that requires the data of its parent.
Vue.js 1.0删除了使用 inherit:true
的能力。可以理解的是,你真的不应该一直在任何地方继承所有东西。
Vue.js 1.0 removed the ability to use inherit: true
. Understandably, you really shouldn't be inheriting everything everywhere all the time.
然而,这是从0.12升级到1.0的问题。我的组件遍布继承
,大多数只是为了能从根获取重要的配置变量 baseurl
零件。这样的变量肯定应该被任何包含链接的组件所知。
This is something of a problem upgrading from 0.12 to 1.0 however. I've got components littered with inherit
, most only so that it can get the important config variable baseurl
from the root component. Such a variable should definitely by known by any component that has a link in it.
< a href ={{baseurl}} /页面>链接< / a>
我可以将配置文件传递给每个组件,但这看起来多余且笨重。
I could pass the prop for config to every single component, but that really seems redundant and clunky.
< c0:config ={baseurl:'example.com'}>< / c0>
< c1:config =config>< / c1>
< c2:config =config>< / c2>
< c3:config =config>< / c3>
为所有组件创建全局范围的任何好方法?
Any good way to create a global scope for all components?
推荐答案
这可能不是最好的解决方案在那里,但它的工作,并没有太多的麻烦。我只是设置了一个getter原型方法。
This might not be the best solution out there, but it works and isn't too much trouble. I just set a getter prototype method.
Vue.prototype.$config = function (key) {
var config = this.$root.$get('config');
if (config) {
return config[key];
}
return '';
}
< a href ={{$ config ('baseurl')}} / page>链接< / a>
任何组件均可访问。
这篇关于在Vue.js中创建一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!