Vue JS - Access root computed property inside a component - vue.js

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 "$";
}
}
}
});

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.

Related

Adding a component by clicking a button

Vue.component('component-a', {
template: '<h3>Hello world!</h3>'
})
new Vue({
el: "#app",
data: {
arr: []
},
methods: {
add(){
this.arr.push('component-a');
console.dir(this.arr)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component-a></component-a>
<hr>
<button #click="add">Add a component</button>
<ul>
<li v-for="component in arr"> {{ component }} </li>
</ul>
</div>
I want to insert a component a lot of times to the page by clicking a butoon, but instead of this only a component`s name is inserted. How to add a component itself?
In your code the double curly braces do not reference the component itself but just the string you added with this.arr.push('component-a'); hence just the string being displayed.
If you would like this string to call the actual component you could use dynamic components.
Replacing {{ component }} with <component :is="component"/> would achieve the effect I think you're looking for.
However if you're only going to be adding one type of component I would consider adding the v-for to the component tag itself like so:
<component-a v-for="component in arr/>
Use the component element to render your component dynamically.
The usage is very simple: <component :is="yourComponentName"></component>
The ":is" property is required, it takes a string (or a component definition).
Vue will then take that provided string and tries to render that component. Of course the provided component needs to be registered first.
All you have to do is to add the component tag as a child element of your list tag:
<li v-for="component in arr">
<component :is="component"></component>
</li>
Vue.component('component-a', {
template: '<h3>Hello world!</h3>'
})
new Vue({
el: "#app",
data: {
arr: []
},
methods: {
add() {
this.arr.push('component-a');
console.dir(this.arr)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component-a></component-a>
<hr>
<button #click="add">Add a component</button>
<ul>
<li v-for="component in arr">
<component :is="component"></component>
</li>
</ul>
</div>

x-template has trouble displaying value on the v-for

I had this issue while trying to render html into a vue component.
I am trying to insert component html through x-template. The issue is when I was trying to display the value {{i.value}} like this it was throwing error on console.
<script type="text/x-template" id="first-template">
<div>
<ul>
<li v-for="i in dataCollection">{{ i.id }}</li>
</ul>
</div>
</script>
Vue.component('menu', {
template: '#first-template',
data() {
return {
dataCollection: [{"id":"01"}, {"id":"02"}, {"id":"03"}],
}
}
});
The error on console was:
But when I was giving value as attribute like:
<script type="text/x-template" id="first-template">
<div>
<ul>
<li v-for="i in dataCollection" :id="i.id"></li>
</ul>
</div>
</script>
it works perfect.
Anyone know any fix ?
You should not put script/x-template tages inside of the element that you mount to the main instance to. Vue 2.0 will read all of its content and try to use it as a template for the main instance, and Vue's virtualDOM treats script/x-template's like normal DOM, which screws everthing up,
Simply moving the template out of the main element solved the problem.
Source
This is a suggestion, not a answer.
As #DmitriyPanov mentioned, you'd better bind unique key when using v-for.
Another issue is you'd better to use non built-in/resevered html elements.
so change component id from menu to v-menu or else you like.
Then simulate similar codes below which are working fine.
I doubt the error is caused by some elements of dataCollection doesn't have key=id (probably you didn't post out all elements). You can try {{ 'id' in i ? i.id : 'None' }}.
Vue.component('v-menu', { //
template: '#first-template',
data() {
return {
newDataCollection: [{"id":"01"}, {"id":"02"}, {"id":"03"}, {'xx':0}],
dataCollection: [{"id":"01"}, {"id":"02"}, {"id":"03"}]
}
}
});
new Vue({
el: '#app',
data() {
return {testProperty: {
'test': '1'
}}
},
methods:{
test: function() {
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<v-menu></v-menu>
</div>
<script type="text/x-template" id="first-template">
<div>
<div style="float:left;margin-right:100px;">
<p>Old:</p>
<ul>
<li v-for="(i, index) in dataCollection" :key="index">{{ i.id }}</li>
</ul>
</div>
<div>
<p>Adjusted:</p>
<ul>
<li v-for="(i, index) in newDataCollection" :key="index">{{ 'id' in i ? i.id : 'None' }}</li>
</ul>
</div>
</div>
</script>
I think the problem here lies in the placement of the X-Template code (I had the same issue). According to the documentation:
Your x-template needs to be defined outside the DOM element to which Vue is attached.
If you are using some kind of CMS, you might end up doing just that.
What helped me in that case was (based on your example):
Placing the X-template script outside the #app
passing the collection as a prop to the v-menu component:
<v-menu v-bind:data-collection="dataCollection"></v-menu>
list dataCollection as a prop inside the v-menu component:
Vue.component('v-menu', { //
template: '#first-template',
props: [ "dataCollection" ],
...
});
I hope that helps anyone.
In 2.2.0+, when using v-for with a component, a key is now required.
You can read about it here https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Component

Display value emitted from Vue component

I created two separated Vue components and I able to emit a message thru a bus.
How can I render/display the message in the component that receives the message.
Example of the Vue component that receives the message:
<template>
<div v-model="cars">
Car model: {{ model }}
<input type="button" #click="display" value="example" />
</div>
</template>
<script>
export default {
data() {
return {
cars: null
}
},
mounted() {
bus.$on('CARS_LOADED', (cars) => {
this.cars = cars;
});
},
methods: {
display()
{
console.log(this.cars);
}
}
}
</script>
I can successfully emit and received the message, however the car model is not updated. I checked the message received and it contains the "model" key with a right value.
I cannot see any error in the Vue console and however if I replace "{{ model }}" by "{{ cars }}" I can see the full message object updated.
I am using Vue 2.x.
Update:
I enclose an example:
https://jsfiddle.net/kvzvxk4f/1/
As you can see in the example I cannot render an specific field from the object, however I can render the object as string.
I think that you are misunderstanding some parts of the vue syntax.
How to access properties of an object:
You just need to write {{ car.model }} to access a property of an object.
How to iterate through an array in a template:
If you want to display all the cars in your template, you should write:
<div v-for="car in cars">
{{ car }}
</div>
As you see, the v-for directive allows you to iterate through an array.
What is v-model?
v-model is used to bind a variable to an input or a component.
<template>
<div>
<input type="text" v-model="foo" />
</div>
</template>
<script>
export default {
data () {
return {
foo: 'bar'
}
}
}
</script>
In that case, the foo property will be bound to the input text.
Last point:
In your case, to make it work, you also need to create a root element for your template, because a template can't have multiple root elements:
<template>
<div>
<div v-for="car in cars">
{{ car }}
</div>
</div>
</div>
I found the answer.
I just have to type property separated by ".". Like for example {{cars.model}}.
<template id="compo2">
<div>
<div>
{{ field.name }}
</div>
<div>
Received: {{ field }}
</div>
</div>
</template>
Example:
https://jsfiddle.net/zuhb7s8q/3/

How to bind extra props to component rendered by v-for?

This is a newbie question but I cannot find answer/hint online:
For a basic template that is rendered by a v-for loop:
<div id="app">
<ul class="list">
<v-ml_component v-for="data_item in get_data.Value"
v-bind:item="data_item"
v-bind:index="data_index"
v-bind:key="data_item.id"
v-bind:messageType="messageType">
</v-ml_component>
</ul>
</div>
<template id="list-template">
<li>
<span v-if="messageType.indexOf('inbox') >= 0">{{ item.MessageId }}</span>
<span>{{index}}</span> : {{ item.Subject }}
</li>
</template>
Everything is straight forward as in basic example, except I need to pass a prop to this component:
$.getJSON(mockAjaxUrl).done(function(ajaxdata){
var messageType = 'inbox';
Vue.component('v-ml_component', {
template:'#list-template',
props:['index', 'item', 'messageType']
});
var vm = new Vue({
el:"#app",
data:{
messageType: messageType,
get_data: ajaxdata
}
});
});
This would get error in console that messageType is not passed to this component. I wonder how the value of this property can be passed to a template that is rendered with a v-for loop?
The messageType prop will be message-type in HTML.
See camelCase vs. kebab-case in the Vue docs.

Vue JS – Using v-if with components

I'm using VueJS components to create a dynamic pricing table. One of the more 'static' elements is a 'most popular' label which is added to the Team plan. I want to be able to use v-if to display a and add an extra class on the plan marked as most popular. I've simplified the code for brevity.
You can see I have tried multiple ways of formatting the expression (currently differs between the v-bind and the v-if) but I'm not sure if this approach is even possible.
Here is the HTML.
<div id="app">
<ul class="plans">
<plan-component :
name="Basic"
most-popular=false
></plan-component>
<plan-component :
name="Recreational"
most-popular=false
></plan-component>
<plan-component :
name="Team"
most-popular=true
></plan-component>
<plan-component :
name="Club"
most-popular=false
></plan-component>
</ul>
<template id="plan-component">
<li v-bind:class="{ 'most-popular': mostPopular == true }">
<template v-if="most-popular === true">
<span class="popular-plan-label">Most popular</span>
</template>
<p>{{ name }}</p>
</li>
</template>
</div>
And here is the JS.
Vue.component('plan-component', {
template: '#plan-component',
props: ['name', 'mostPopular'],
});
new Vue({
el: '#app';
});
You need to validate the mostPopular property type, since it's Boolean it won't work when you place most-popular=true because it's considered as a string "true" not true instead put most-popular tag on popular plan only. Here is example:
Vue.component('plan-component', {
template: '#plan-component',
props: {
name: String,
mostPopular: {
type: Boolean,
default: false,
}
},
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.25/vue.min.js"></script>
<div id="app">
<ul class="plans">
<plan-component name="Basic"></plan-component>
<plan-component name="Recreational"></plan-component>
<plan-component name="Team" most-popular></plan-component>
<plan-component name="Club"></plan-component>
</ul>
</div>
<template id="plan-component">
<li v-bind:class="{ 'most-popular': mostPopular }">
<p>{{ name }} <small v-if="mostPopular" class="popular-plan-label" style="color: red">Most popular</small></p>
</li>
</template>
Use <template v-if="ok"> for conditional rendering.