2将道具对象传递给子组件并检索

2将道具对象传递给子组件并检索

本文介绍了Vuejs 2将道具对象传递给子组件并检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

父组件

 <模板>

<子组件 :v-bind="props"></child-component></div></模板><脚本>从ChildComponent.vue"导入 ChildComponent;导出默认 {名称:'父组件',挂载(){},道具: {名字:'用户名',姓氏:'用户姓氏'富:'酒吧'},组件: {子组件},方法: {}}</脚本><样式范围></风格>

子组件

<模板>

</div></模板>导出默认 {名称:'子组件',挂载(){控制台.log(this.props)}}</脚本>
解决方案

就这么简单:

父组件:

<模板>

<my-component :propObj="anObject"></my-component></div></模板><脚本>从ChildComponent.vue"导入 ChildComponent;导出默认 {名称:'父组件',挂载(){},道具: {一个对象:对象},组件: {子组件},}</脚本><样式范围></风格>

子组件:

导出默认{道具: {//type, required 和 default 是可选的,你可以把它简化为'options: Object'propObj: { type: Object, required: false, default: {"test": "wow"}},}}

这应该可行!

还可以查看 props 文档:
https://vuejs.org/v2/guide/components.html#Props

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

https://vuejs.org/v2/guide/components.html#同步修饰符

I was wondering how to pass an object to a child component using props and retrieving. I understand how to do it as attributes but how to pass an object and retrieve the object from the child component? When I use this.props from the child component I get undefined or an error message.

Parent component

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

Child component

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

Simple as that:

Parent component:

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

Child component:

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

This should work!

Take a look at props docs also:
https://vuejs.org/v2/guide/components.html#Props

If you want to sent data from the child to the parent as was already pointed in the comments you have to use events or take a look at 'sync' feature which is available in 2.3 +

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

这篇关于Vuejs 2将道具对象传递给子组件并检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:28