我正在尝试从根 Vue 实例访问计算属性并在组件内部访问它。这<p class="currency">
在组件模板外部输出的元素正确输出 {{currency }},但是当尝试访问组件内部的 {{currency}} 时,不会输出任何内容。我尝试过将货币设置为道具,但这似乎没有任何区别。我确信必须有一种方法可以从组件内访问根 Vue 实例,例如 {{ vm.currency }} 但我再次尝试过,但没有成功。
这是 HTML。
<div id="app">
<ul class="plans">
<plan-component : name="Basic" ></plan-component>
<plan-component : name="Rec" ></plan-component>
<plan-component : name="Team" ></plan-component>
<plan-component : name="Club" ></plan-component>
</ul>
<template id="plan-component">
<li>
<h2 class="plan-name">{{ name }}</h2>
<h3 class="plan-cost">{{ currency }}</h3>
</li>
</template>
<p class="currency">{{ currency }}</p>
</div><!-- end #app -->
这里是JS。变量countryCode是在我的应用程序中的其他地方定义的,但就像我所说的{{currency}}在组件外部工作,所以这不是问题。
Vue.component('plan-component', {
template: '#plan-component',
props: {
name: String,
}
});
var vm = new Vue({
el: '#app',
computed: {
currency: function() {
if(countryCode === 'GB') {
return "£";
} else {
return "$";
}
}
}
});
对于遇到相同问题的任何人,您只需在属性之前定义 $root 即可。所以在我的例子中而不是这个......
<h3 class="plan-cost">{{ currency }}</h3>
……应该是这个……
<h3 class="plan-cost">{{ $root.currency }}</h3>
VueJS 文档确实在以下内容中讨论过这一点母链 https://vuejs.org/guide/components.html#Parent-Chain组件部分。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)