使用 VUE 2.0 和 VUEX 我对如何将数据从parent
传递到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>
我通过名为“triads”的数组循环:
state: {
triads: [
{
people: [],
places: [],
equipment: []
}
]
}
我想将triad
变量发送到<people />
,<places />
和<equipment />
。
如何将父模板中的内容添加到子模板?谢谢。
答案 0 :(得分:3)
您只需要将PROP添加到您的子组件,然后绑定数据。
E.g。 <people :yourProp='triad'>
在您的子组件中(根据文档:satelize):
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>'
})
您不需要vuex来传递数据。您需要Vuex在组件之间共享状态(双向)。
答案 1 :(得分:2)
你可以通过道具传递属性
<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>
并在每个子组件中,提到像这样的道具:
export default {
props: ['someproperty']
}
我认为您的父组件也无法直接访问该属性,因此您可以使用父级中的mapGetters来访问它,同时,您的状态也会有一个getter。
state: {
triads: [
{
people: [],
places: [],
equipment: []
}
]
},
getters: {
getTriads: (state) => {
return state.triads
}
}
现在,您可以在父级中使用mapGetters:
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
'triads': 'getTriads'
})
}
}
如果设置太多,请尝试此
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
}
}
}