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

时间:2017-07-18 18:40:52

标签: components vuejs2

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

父组件

FirebaseDatabase database;
DatabaseReference myRef;

database = FirebaseDatabase.getInstance();
myRef = database.getReference("kraj");

子组件

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

2 个答案:

答案 0 :(得分:15)

简单:

父组件:

<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

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

中可用

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

答案 1 :(得分:0)

这是将许多道具作为对象传递到组件中的简单解决方案

父项:

<template>
  <div>
    <!-- different ways to pass in props -->
    <my-component v-bind="props"></my-component>     
    <my-component :firstname="props.firstname" :lastname="props.lastname" :foo="props.foo">
    </my-component>     
  </div>
</template>

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

  export default {
    name: 'ParentComponent',
    props: {
      firstname: 'UserFirstName',
      lastname: 'UserLastName'
      foo:'bar'
    },
    components: {
      ChildComponent
    }
  }
</script>

子组件:

<template>
  <div>
  </div>
</template>
<script>
export default {
  name: 'ChildComponent',
  props: ['firstname', 'lastname', 'foo'],
  mounted() {
    console.log(this.props)
  }  
}
</script>
相关问题