【问题标题】:Vuejs 2 Passing prop object to child component and retrievingVuejs 2将道具对象传递给子组件并检索
【发布时间】:2017-12-23 18:53:40
【问题描述】:

我想知道如何使用道具和检索将对象传递给子组件。我了解如何将其作为属性来执行,但如何传递对象并从子组件中检索对象?当我从子组件中使用 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>

【问题讨论】:

  • 1) 您没有在父组件上正确定义道具。 2)您不能通过v-bind="props" 传递父组件的道具。 3) 如果您通过v-bind 将道具值的对象传递给子组件,您仍然需要在子组件中定义这些道具。 4) 从子组件“检索”数据是通过事件完成的。 5) 请阅读Vue components上的文档
  • 我不需要使用 v-bind。我从一个例子中得到了它并尝试使用它。我正在寻找实现这一目标的正确方法。我现在正在查看 Vue 组件文档

标签: components vuejs2


【解决方案1】:

就这么简单:

父组件:

<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://vuejs.org/v2/guide/components.html#Props

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

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

【讨论】:

  • 如果您只想为 propObj 的属性设置默认值怎么办?默认道具初始化不会触发,因为整个对象道具不是空的。
【解决方案2】:

这是一个简单的解决方案,可以将许多道具作为对象传递给组件

父组件:

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

【讨论】:

  • console.log(this.props) 返回undefined
猜你喜欢
  • 1970-01-01
  • 2018-08-10
  • 2020-11-23
  • 2019-07-11
  • 1970-01-01
  • 2018-07-07
  • 2019-01-22
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多