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

2024-04-28

我想知道如何使用 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>

子组件

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

就那么简单:

父组件:

<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"}},
  }
}

这应该有效!

另请查看 props 文档:
https://v2.vuejs.org/v2/guide/components.html#Props https://v2.vuejs.org/v2/guide/components.html#Props

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vuejs 2 将 prop 对象传递给子组件并检索 的相关文章

随机推荐