2017-02-14 32 views
1

使用VUE 2.0VUEX我有点困惑如何将数据传递从parentchildVUE/VUEX:如何将数据传递从父模板儿童模板

<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> 

循环通过阵列名为 “打黑”:

state: { 
    triads: [ 
    { 
     people: [], 
     places: [], 
     equipment: [] 
    } 
    ] 
} 

我想将triad变量发送到<people /><places /><equipment />


我如何从父模板子模板内容?谢谢。

+0

是人,地点和设备分离组件? –

+0

是的,他们是;-)我只是想分发数据 – Timo

回答

3

您只需要将PROP添加到您的子组件,然后绑定数据。

E.g. <people :yourProp='triad'>

在你的孩子的组件(按照文档:https://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>' 
}) 

你不需要vuex只是传递数据。您需要Vuex在组件之间共享状态(双向)。

+0

好,你能更深入地解释它吗?我对vue和vuex很新颖。但是谢谢。 – Timo

+0

编辑给你更多的解释和一些文档参考 –

+0

是的,它的工作原理。你是我的主人! – Timo

1

您可以通过道具

<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来访问同时,它也表明你的国家也有吸气。现在

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 
    } 
    } 
} 
相关问题