programing

Vuejs 2 소품 개체를 하위 구성 요소에 전달하고 검색

sourcejob 2022. 8. 12. 23:11
반응형

Vuejs 2 소품 개체를 하위 구성 요소에 전달하고 검색

소품이나 검색을 사용하여 아이 컴포넌트에 오브젝트를 건네주는 방법이 궁금했습니다.속성으로 수행하는 방법은 이해하지만 개체를 전달하고 하위 구성 요소에서 개체를 가져오는 방법은 무엇입니까?하위 컴포넌트에서 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"}},
  }
}

이거면 될 거야!

소품 문서도 참조해 주세요.
https://vuejs.org/v2/guide/components.html#Props

이미 코멘트에서 지적된 대로 자녀로부터 부모에게 데이터를 전송하려면 이벤트를 사용하거나 2.3+에서 사용할 수 있는 '동기화' 기능을 확인해야 합니다.

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

여기 많은 소품을 하나의 컴포넌트로 전달하기 위한 간단한 솔루션이 있습니다.

상위 컴포넌트:

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

언급URL : https://stackoverflow.com/questions/45174669/vuejs-2-passing-prop-object-to-child-component-and-retrieving

반응형