2017-07-18 57 views
2

我想知道如何使用道具和檢索將對象傳遞給子組件。我知道如何做它的屬性,但如何傳遞一個對象,並從子組件檢索對象?當我從子組件中使用this.props時,我得到未定義的或錯誤消息。Vuejs 2將prop對象傳遞給子組件並檢索

父組件

<template> 
     <div> 
     <my-component :v-bind="props"></my-component>  
     </div> 
    </template> 

<script> 
import ChildComponent from "ChildComponent.vue"; 

export default { 
    name: 'ParentComponent', 
    mounted() { 

    }, 
    props: { 
     firstname: 'UserFirstName', 
     lastname: 'UserLastName' 
     foo:'bar' 
    }, 
    components: { 
    ChildComponent 
    }, 
    methods: { 

     } 
} 
</script> 

<style scoped> 
</style> 

子組件

<script> 
<template> 
    <div> 
    </div> 
</template> 
export default { 
    name: 'ChildComponent', 
    mounted() { 
    console.log(this.props) 
    } 
} 
</script> 
+0

1)您沒有正確地定義你的道具父組件可用。 2)你不能通過'v-bind =「props」'傳遞你的父組件的道具。 3)如果你通過'v-bind'傳遞一個道具值對象給子組件,你仍然需要在子組件中定義這些道具。 4)通過事件完成「從子組件中檢索」數據。 5)請閱讀[Vue組件]的文檔(https://vuejs.org/v2/guide/components.html) – thanksd

+0

我不需要使用v-bind。我從一個例子中得到了它並嘗試使用它。我正在尋找實現這一目標的正確方法。我現在正在查看Vue組件文檔 – icode

回答

3

就這麼簡單:

父組件:

<template> 
    <div> 
    <my-component :propObj="anObject"></my-component>  
    </div> 
</template> 

<script> 
import ChildComponent from "ChildComponent.vue"; 

export default { 
    name: 'ParentComponent', 
    mounted() { }, 
    props: { 
     anObject: Object 
    }, 
    components: { 
     ChildComponent 
    }, 
} 
</script> 

<style scoped> 
</style> 

子組件:

export default { 
    props: { 
    // type, required and default are optional, you can reduce it to 'options: Object' 
    propObj: { type: Object, required: false, default: {"test": "wow"}}, 
    } 
} 

這應該工作!

看看道具文檔也:
https://vuejs.org/v2/guide/components.html#Props

如果要發送的數據,從孩子的父母在你必須使用事件或看看「同步的評論已經指出「功能,它是2.3 +

https://vuejs.org/v2/guide/components.html#sync-Modifier

+0

如果您想僅將默認值設置爲propObj的屬性,該怎麼辦?由於整個對象prop不爲空,默認的prop初始化不會觸發。 – Storm