vue.js - Vue JS - 访问组件内的根计算属性

标签 vue.js

我试图从根 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/

相关文章:

javascript - 如何通过应用程序使用对话框,向其传递内容

javascript - vue.js动态添加输入v-model不起作用

javascript - 是否可以在created()完成后运行v-for?

vue.js - `vue-cli-service build` 不生成模板的代码

vue.js - 在生产构建中更改 js 和 css 文件的文件路径

Laravel Echo 不监听推送事件

vue.js - Vue 路由器。 Root Vue没有数据?

docker - Vue UI 无法通过 docker-compose 工作

arrays - 虚拟化 : How to do a v-select search in array of arrays

npm - [Vue 警告] : Failed to mount component: template or render function not defined