7

I'm attempting to access a computed property from the root Vue instance and access it inside a component. The <p class="currency"> element which is output outside of the component template outputs {{ currency }} correctly, but when trying to access {{ currency }} inside of the component nothing is output. I have tried setting currency as a prop but this doesn't appear to make any difference. I'm sure there must be a way to access the root Vue instance from within the component, something like {{ vm.currency }} but again I have tried this to no avail.

Here is the 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 -->

Here is the JS. The variable countryCode is defined elsewhere in my app, but like I said {{ currency }} is working outside of the component so this isn't an issue.

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 "$";
      }
    }
  }
});
2
  • where from countryCode is coming ? Commented Jul 11, 2016 at 11:47
  • 1
    It says this in the question: "The variable countryCode is defined elsewhere in my app, but like I said {{ currency }} is working outside of the component so this isn't an issue." Commented Jul 11, 2016 at 12:04

1 Answer 1

11

For anyone with the same issue, you simply need to define $root before the property. So in my example instead of this...

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

...it needs to be this...

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

The VueJS docs do talk about this under the Parent Chain section of Components.

Sign up to request clarification or add additional context in comments.

2 Comments

You can also use vuex to do this
It's also possible to create a computed property: computed: { currency() { return this.$root.currency } } and then use it in HTML just as {{ currency }}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.