Reputation: 261
Using VUE 2.0 and VUEX I am a bit confused about how to pass data from parent
to child
.
<template>
<div id="app" class="container">
<div class="card" v-for="(triad, index) in triads">
<div class="row">
<div class="col-sm-4">
<people />
</div>
<div class="col-sm-4">
<places />
</div>
<div class="col-sm-4">
<equipment />
</div>
</div>
</div>
</div>
</template>
I am looping through an array named "triads":
state: {
triads: [
{
people: [],
places: [],
equipment: []
}
]
}
I want to send the triad
variable to <people />
, <places />
and <equipment />
.
How do I get the content from the parent template to the child template? Thank you.
Upvotes: 2
Views: 3205
Reputation: 13644
You just need to add PROP to your child components and then bind data.
E.g. <people :yourProp='triad'>
In your child components (as per docs: https://v2.vuejs.org/v2/guide/components.html#Props):
Vue.component('people', {
// declare the props
props: ['yourProp'],
// just like data, the prop can be used inside templates
// and is also made available in the vm as this.message
template: '<span>{{ yourProp }}</span>'
})
you do not need vuex to just pass data. You need Vuex to share states between components (bi-directional).
Upvotes: 3
Reputation: 9549
you can pass the properties down by the means of props
<template>
<div id="app" class="container">
<div class="card" v-for="(triad, index) in triads">
<div class="row">
<div class="col-sm-4">
<people :someproperty='triad'></people>
</div>
<div class="col-sm-4">
<places :someproperty='triad'></places>
</div>
<div class="col-sm-4">
<equipment :someproperty='triad'></equipement>
</div>
</div>
</div>
</div>
</template>
and inside each of these children components, mention the props like so:
export default {
props: ['someproperty']
}
I think your parent component too doesnt have access to the property directly, so you could use mapGetters in the parent to have access to it, at the same time, it follows that your state too has a getter.
state: {
triads: [
{
people: [],
places: [],
equipment: []
}
]
},
getters: {
getTriads: (state) => {
return state.triads
}
}
Now, you can use mapGetters in your parent:
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
'triads': 'getTriads'
})
}
}
If that is too much of a setup, just try this
export default {
computed: {
triads () {
/**
* You could also try, return this.$store.state.triads
* but DONT do that, that defeats the purpose of using vuex.
*/
return this.$store.getters.getTriads
}
}
}
Upvotes: 3