How to pass props to child component in vue - javascript

I have a parent component where I am doing the API call and getting the response. So what I am trying to do is pass this response as a prop to child component in Vue.
So here is my parent component and the call:
<button class="btn button col-2" #click="addToCart()">
Add to cart
</button>
addToCart: function () {
let amount = this.itemsCount !== "" ? this.itemsCount : 1;
if(this.variationId != null) {
this.warningMessage = false;
cartHelper.addToCart(this.product.id, this.variationId, amount, (response) => {
this.cartItems = response.data.attributes.items;
});
} else {
this.warningMessage = true;
}
},
So I want to pass this "this.cartItems" to the child component which is:
<template>
<div
class="dropdown-menu cart"
aria-labelledby="triggerId"
>
<div class="inner-cart">
<div v-for="item in cart" :key="item.product.id">
<div class="cart-items">
<div>
<strong>{{ item.product.name }}</strong>
<br/> {{ item.quantity }} x $45
</div>
<div>
<a class="remove" #click.prevent="removeProductFromCart(item.product)">Remove</a>
</div>
</div>
</div>
<hr/>
<div class="cart-items-total">
<span>Total: {{cartTotalPrice}}</span>
Clear Cart
</div>
<hr/>
<router-link :to="{name: 'order'}" class="btn button-secondary">Go To Cart</router-link>
</div>
</div>
</template>
<script>
export default {
computed: {
},
methods: {
}
};
</script>
So I am quite new in vue if you can help me with thi, I would be really glad.

Passing props is quite simple. If cartItems is what you wan´t to pass as a prop, you can do this:
<my-child-component :cartItems="cartItems"></my-child-component>
In this case you implemented your child as myChildComponent. You pass cartItems with :cartItems="cartItems" to it. In your child you do this:
props: {
cartItems: Object
}
Now you can use it with this.cartItems in your methods or {{cartItems}} in your themplate.

Vue.component('Child', {
template: `
<div class="">
<p>{{ childitems }}</p>
</div>
`,
props: ['childitems']
})
new Vue({
el: '#demo',
data() {
return {
items: []
}
},
methods: {
getItems() {
//your API call
setTimeout(() => {
this.items = [1, 2]
}, 2000);
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<button #click="getItems">get data</button>
<Child v-if="items.length" :childitems="items" />
</div>
You can wait for response, and when you gate this.cartItems then render your child component with a v-if="this.cartItems.length" condition

Related

Vue - how to append components?

I'm trying to create a button that, once is pushed, adds a child component to my component. My code works, except that the HTML is being parsed as a string, here is the parent component:
<template>
<div id="app">
<li v-for="item in items">
{{ item.component }}
</li>
</div>
</template>
<script>
export default {
props:{},
data(){
return {
items: []
}
},
mounted() {},
computed: {},
methods: {
addItem(){
this.items.push({component: '<testcomponent />'})
}
}
}
</script>
And the child component is very basic:
<template>
<div id="app">
<h1>Testing</h1>
</div>
</template>
So the problem with my code is that, every time i push the button, instead of loading every time a new instance of the child component, it will parse the HTML as a string: '<testcomponent />'. How can i fix this? Thanks in advance!
You can push the component name, and use <component :is="item.component"/> in the v-for as follows:
const testcomponent = Vue.component('testcomponent', {
template: '#testcomponent',
});
new Vue({
el:"#app",
components: { testcomponent },
data() { return { items: [] } },
methods: {
addItem() {
this.items.push({ component: 'testcomponent' });
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template id="testcomponent">
<div><h1>Testing</h1></div>
</template>
<div id="app">
<button #click="addItem">Add</button>
<li v-for="item in items">
<component :is="item.component"/>
</li>
</div>

Vue, separate component fires off 'not a function' message

Everything here displays and acts how i want except for my call to the setInputName function. I believe the reason for this is because that happens within the tabs component which is built on a separate component and template, which then uses another component/template tab for the individual list item tabs.
The problem here is that when I click my list items, the console prints that _vm.setInputName is not a function
How can I fix this to be able to call this function from within the rendered template?
<tabs>
<tab name="Activity" :selected="true">
<div class="row notesInput" id="notesInput">
<div class="col-lg-12">
<div class="tabs">
<ul style="border-bottom:none !important; text-decoration:none">
<li v-on:click="setInputName('public')">Public</li>
<li v-on:click="setInputName('public')">Internal</li>
</ul>
</div>
<div>
<input type="text" v-bind:name="inputName">
<br>
Input name is: {{ inputName }}
</div>
</div>
</div>
</tab>
</tabs>
<script>
Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }">
<a :href="tab.href" #click="selectTab(tab)">{{ tab.name }}</a>
</li>
</ul>
</div>
<div class="tabs-details">
<slot></slot>
</div>
</div>
`,
data() {
return {
tabs: [],
};
},
created() {
this.tabs = this.$children;
},
methods: {
selectTab(selectedTab) {
this.tabs.forEach(tab => {
tab.isActive = tab.name == selectedTab.name;
});
} } });
Vue.component('tab', {
template: `
<div v-show="isActive"><slot></slot></div>
`,
props: {
name: { required: true },
selected: { default: false } },
data() {
return {
isActive: false,
};
},
computed: {
href() {
return '#' + this.name.toLowerCase().replace(/ /g, '-');
} },
mounted() {
this.isActive = this.selected;
} });
export default {
components: {
Multipane,
MultipaneResizer,
},
data () {
return {
inputName: '',
}
},
computed: {
},
methods: {
setInputName(str) {
this.inputName = str;
}
};
</script>
I think the issue is because you are calling the function from another component.
but your function is in another function. If you want this to work then you should extend your component in which your function exists and then you can use it.

How render component in v-for by button from parent

How i can render v-if component by button(button in parent) click inside v-for loop? and should render only in that item where clicked
<div v-for="item in items">
<button #click >Show child<button>
<div>{{item.name}}</div>
<child v-if="this button clicked" :item="item"><child>
<div>
You have to store info about state of every item (if it was clicked) in your data. Then, when you click on button you should update clicked property for particular item. Finally if item.clicked is set on true you will show your child component (or any other html).
<template>
<div>
<div v-for="item in items" :key="item.id">
<button #click="item.clicked = true" >Show child</button>
{{item.name}}
<div v-if="item.clicked">Item child</div>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data: function() {
return {
items: [
{
id: 1,
name: 'test1',
clicked: false
},
{
id: 2,
name: 'test2',
clicked: false
},
{
id: 3,
name: 'test3',
clicked: false
}
]
}
}
}
</script>
Plain and simple you just have to set some flag for latter v-if:
<div id="app">
<div v-for="item in items">
<button #click="$set(item, 'shown', true)">Show child</button>
<div>{{ item.name }}</div>
<div v-if="item.shown">Child component</div>
</div>
</div>
Here, $set() is used because initial item could lack shown field, so setting it directly with item.shown=true won't be reactive.
You can also hide button after click:
<button #click="$set(item, 'shown', true)" v-if="!item.shown">Show child</button>
To toggle visibility you just have to do it like this:
<button #click="$set(item, 'shown', !item.shown)">
{{ item.shown ? 'Hide' : 'Show' }} child
</button>
JSFiddle
You can take advantage of an item... index available in v-for directive (e.g. v-for="(item, i) in items"), to bind it (index of the item) to the function which shows an item by changing it's property:
Update: Initial answer has been deleted after requirements refinement.
Since you prefer to keep from mutation of items, you can wrap them in Map object (as keys) and keep visibility settings separately as Map values. Unfortunately, as far as I know, for the time being Vue.js does not support reactivity for Map objects, that's why I have to trigger rerendering manually by using forceUpdate:
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('child', {
template: '<p>Visible child</p>'
})
new Vue({
el: "#demo",
template: `
<div>
<div v-for="item in items">
<button #click="toggleChild(item)">Toggle child</button>
<div>{{item.name}}</div>
<child v-if="isVisible(item)" :item="item"></child>
</div>
</div>
`,
data () {
return {
itemsMap: new Map(
[
{ name: 'test1' },
{ name: 'test2' }
].map(item => [item, { visible: false }])
)
};
},
methods: {
toggleChild(item) {
this.itemsMap.set(item, { visible: !this.itemsMap.get(item).visible });
this.$forceUpdate();
},
isVisible(item) {
return this.itemsMap.get(item).visible;
}
},
computed: {
items: function() {
return Array.from(this.itemsMap.keys());
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo"></div>

Vue.js computed property loses its reactivity when passed through an event

I have a Modal component in my main app that gets passed content via an event whenever a modal has to be shown. Modal content is always a list with an action associated with each item, like "select" or "remove":
Vue.component('modal', {
data() {
return {
shown: false,
items: [],
callback: ()=>{}
}
},
mounted() {
EventBus.$on('showModal', this.show);
},
template: `<ul v-if="shown">
<li v-for="item in items">
{{ item }} <button #click="callback(item)">Remove</button>
</li>
</ul>`,
methods: {
show(items, callback) {
this.shown = true;
this.items = items;
this.callback = callback;
}
}
});
Sadly, when passing a computed property to that modal like in the component below, the reactive link gets broken -> if the action is "remove", the list is not updated.
Vue.component('comp', {
data() {
return {obj: {a: 'foo', b: 'bar'}}
},
computed: {
objKeys() {
return Object.keys(this.obj);
}
},
template: `<div>
<button #click="showModal">Show Modal</button>
<modal></modal>
</div>`,
methods: {
remove(name) {
this.$delete(this.obj, name);
},
showModal() {
EventBus.$emit('showModal', this.objKeys, this.remove);
}
}
});
See the minimal use case in this fiddle: https://jsfiddle.net/christophfriedrich/cm778wgj/14/
I think this is a bug - shouldn't Vue remember that objKeys is used for rendering in Modal and update it? (The forwarding of the change of obj to objKeys works.) If not, what am I getting wrong and how could I achieve my desired result?
You have the modal working with its own copy of items:
template: `<ul v-if="shown">
<li v-for="item in items">
{{ item }} <button #click="callback(item)">Remove</button>
</li>
</ul>`,
methods: {
show(items, callback) {
this.shown = true;
this.items = items;
this.callback = callback;
}
}
That copy is made once, upon the call to show, and what you are copying is just the value of the computed at the time you emit the showModal event. What show receives is not a computed, and what it assigns is not a computed. It's just a value.
If, anywhere in your code, you made an assignment like
someDataItem = someComputed;
the data item would not be a functional copy of the computed, it would be a snapshot of its value at the time of the assignment. This is why copying values around in Vue is a bad practice: they don't automatically stay in sync.
Instead of copying values around, you can pass a function that returns the value of interest; effectively a get function. For syntactic clarity, you can make a computed based on that function. Then your code becomes
const EventBus = new Vue();
Vue.component('comp', {
data() {
return {
obj: {
a: 'foo',
b: 'bar'
}
}
},
computed: {
objKeys() {
return Object.keys(this.obj);
}
},
template: `<div>
<div>Entire object: {{ obj }}</div>
<div>Just the keys: {{ objKeys }}</div>
<button #click="remove('a')">Remove a</button>
<button #click="remove('b')">Remove b</button>
<button #click="showModal">Show Modal</button>
<modal></modal>
</div>`,
methods: {
remove(name) {
this.$delete(this.obj, name);
},
showModal() {
EventBus.$emit('showModal', () => this.objKeys, this.remove);
}
}
});
Vue.component('modal', {
data() {
return {
shown: false,
getItems: null,
callback: () => {}
}
},
mounted() {
EventBus.$on('showModal', this.show);
},
template: `<div v-if="shown">
<ul v-if="items.length>0">
<li v-for="item in items">
{{ item }} <button #click="callback(item)">Remove</button>
</li>
</ul>
<em v-else>empty</em>
</div>`,
computed: {
items() {
return this.getItems && this.getItems();
}
},
methods: {
show(getItems, callback) {
this.shown = true;
this.getItems = getItems;
this.callback = callback;
}
}
});
var app = new Vue({
el: '#app'
})
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
<comp></comp>
</div>
You are passing a value to a function, you are not passing a prop to a component. Props are reactive, but values are just values. You include modal in the template of comp, so rework it to take (at least) items as a prop. Then it will be reactive.
I would recommend having the remove process follow the emit-event-and-process-in-parent rather than passing a callback.
const EventBus = new Vue();
Vue.component('comp', {
data() {
return {
obj: {
a: 'foo',
b: 'bar'
}
}
},
computed: {
objKeys() {
return Object.keys(this.obj);
}
},
template: `<div>
<div>Entire object: {{ obj }}</div>
<div>Just the keys: {{ objKeys }}</div>
<button #click="remove('a')">Remove a</button>
<button #click="remove('b')">Remove b</button>
<button #click="showModal">Show Modal</button>
<modal :items="objKeys" event-name="remove" #remove="remove"></modal>
</div>`,
methods: {
remove(name) {
this.$delete(this.obj, name);
},
showModal() {
EventBus.$emit('showModal');
}
}
});
Vue.component('modal', {
props: ['items', 'eventName'],
data() {
return {
shown: false,
}
},
mounted() {
EventBus.$on('showModal', this.show);
},
template: `<div v-if="shown">
<ul v-if="items.length>0">
<li v-for="item in items">
{{ item }} <button #click="emitEvent(item)">Remove</button>
</li>
</ul>
<em v-else>empty</em>
</div>`,
methods: {
show(items, callback) {
this.shown = true;
},
emitEvent(item) {
this.$emit(this.eventName, item);
}
}
});
var app = new Vue({
el: '#app'
})
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
<comp></comp>
</div>

How can I periodically update my component in VueJS

I have a component in Vue that looks like this:
<template>
<div id="featured_top">
<i class="i-cancel close"></i>
<div v-for="item in toplist">
<div class="featured-item" v-lazy:background-image="poster(item)">
<a class="page-link" :href="url(item)" target="_blank">
<h4 class="type"> Featured Movie </h4>
<div class="title">{{ item.title }}</div>
</a>
</div>
</div>
</div>
</template>
<script>
const _ = require('lodash')
export default {
name: 'featured',
computed: {
toplist () {
return _.sampleSize(this.$store.state.toplist, 3)
}
},
methods: {
poster: function (item) {
return 'https://example.com/' + item.backdrop_path
},
url: function (item) {
return 'http://example.com/' + item.id
}
}
}
</script>
I choose three random items from the store hen rendering the component, iterate over and display then. However, this seems too static so I'd like periodically update the component so it randomises the items again.
I'm new to Vue2 - any ideas on what trivial bit I'm missing?
Your use-case is not completely clear to me but if you'd like to randomize with an interval. You could change your computation to a method and call this function with setInterval.
Something like in the demo below or this fiddle should work.
(In the demo I've removed the lazy loading of the image to reduce the complexity a bit.)
// const _ = require('lodash')
const testData = _.range(1, 10)
.map((val) => {
return {
title: 'a item ' + val
}
})
const store = new Vuex.Store({
state: {
toplist: testData
}
})
//export default {
const randomItems = {
name: 'featured',
template: '#tmpl',
computed: {
/*toplist () {
return _.sampleSize(this.$store.state.toplist, 3)
}*/
},
created() {
this.getToplist() // first run
this.interval = setInterval(this.getToplist, 2000)
},
beforeDestroy() {
if (this.interval) {
clearIntervall(this.interval)
this.interval = undefined
}
},
data() {
return {
interval: undefined,
toplist: []
}
},
methods: {
getToplist() {
this.toplist = _.sampleSize(this.$store.state.toplist, 3)
},
poster: function(item) {
return 'https://example.com/' + item.backdrop_path
},
url: function(item) {
return 'http://example.com/' + item.id
}
}
}
new Vue({
el: '#app',
template: '<div><random-items></random-items</div>',
store,
components: {
randomItems
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="app">
</div>
<script type="text/template" id="tmpl">
<div id="featured_top">
<i class="i-cancel close"></i>
<div v-for="item in toplist">
<div class="featured-item" v-lazy:background-image="poster(item)">
<a class="page-link" :href="url(item)" target="_blank">
<h4 class="type"> Featured Movie </h4>
<div class="title">{{ item.title }}</div>
</a>
</div>
</div>
</div>
</script>

Categories

Resources