Vuejs 2将prop对象传递给子组件并检索

ico*_*ode 11 components vuejs2

我想知道如何使用props和检索将对象传递给子组件.我理解如何将其作为属性,但如何传递对象并从子组件中检索对象?当我从子组件使用this.props时,我得到未定义或错误消息.

父组件

 <template>
        <div>
        <child-component :v-bind="props"></child-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>
Run Code Online (Sandbox Code Playgroud)

儿童组件

<script>
<template>
   <div>
   </div>
</template>
export default {
    name: 'ChildComponent',
    mounted() {
    console.log(this.props)
  }  
}
</script>
Run Code Online (Sandbox Code Playgroud)

V. *_*bor 18

就那么简单:

父组件:

<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>
Run Code Online (Sandbox Code Playgroud)

子组件:

export default {
  props: {
    // type, required and default are optional, you can reduce it to 'options: Object'
    propObj: { type: Object, required: false, default: {"test": "wow"}},
  }
}
Run Code Online (Sandbox Code Playgroud)

这应该工作!

看一下道具文档:https:
//vuejs.org/v2/guide/components.html#Props

如果您想要将孩子的数据发送到父级,就像评论中已经指出的那样,您必须使用事件或者查看2.3 +中提供的"同步"功能

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