我试图从根 Vue 实例访问计算属性并在组件内部访问它。 <p class="currency">
在组件模板外部输出的元素会正确输出 {{ currency }},但是当尝试访问组件内部的 {{ currency }} 时,不会输出任何内容。我试过将货币设置为 Prop ,但这似乎没有任何区别。我确定必须有一种方法可以从组件内部访问根 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 文档确实在 Parent Chain 下讨论了这个问题组件部分。
关于vue.js - Vue JS - 访问组件内的根计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304466/