【问题标题】:Vue JS - Access root computed property inside a componentVue JS - 访问组件内的根计算属性
【发布时间】:2016-07-11 10:18:27
【问题描述】:

我正在尝试从根 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 "$";
      }
    }
  }
});

【问题讨论】:

  • countryCode 来自哪里?
  • 它在问题中这样说:“变量 countryCode 在我的应用程序的其他地方定义,但就像我说的 {{ currency }} 在组件之外工作,所以这不是问题。”

标签: vue.js


【解决方案1】:

对于遇到相同问题的任何人,您只需在属性之前定义 $root 即可。所以在我的例子中,而不是这个......

<h3 class="plan-cost">{{ currency }}</h3>

...应该是这个...

<h3 class="plan-cost">{{ $root.currency }}</h3>

VueJS 文档确实在组件的 Parent Chain 部分讨论了这一点。

【讨论】:

  • 你也可以使用vuex来做到这一点
  • 也可以创建一个计算属性:computed: { currency() { return this.$root.currency } },然后像{{ currency }}一样在HTML中使用它。
猜你喜欢
  • 2018-01-14
  • 2020-09-30
  • 2018-08-03
  • 1970-01-01
  • 2017-06-30
  • 2019-05-05
  • 2019-09-22
  • 2019-03-16
  • 2018-01-22
相关资源
最近更新 更多