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 "$";
}
}
}
});
You can put a watcher on any reactive property. This includes computed props, props, as well as data that is specified inside of data() on your Vue component. They're really useful for creating side effects — things that don't update your application's state immediately.
Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!
We can access the root instance of from a child component with the $root property. The code above created a rootFoo computed property from the root Vue instance's foo component and displayed it inside the foo component. So we get foo displayed.
Computed properties are used to calculate the value of a property based on some other conditions. Watchers, on the other hand, are not primarily used for changing the value of a property; instead, they are used to notify you when the value has changed and let you perform certain actions based on these changes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With