vue/vue기초

#4.vue기초 props 활용

샐님 2021. 9. 1. 01:44
728x90
반응형

* props 로 데이터 전달 시 숫자, 객체, 문자열등 다양한 형태로 전달 가능

 

1. User.vue -부모 컨포넌트(객체 데이터 전달)

<template>
  <div class="blue lighten-3 pa-3">
    <h1>User Info</h1>
    <p>User Name is {{name}}</p> 
    <button @click="nameChange">Name Change</button>
    <hr>
    <v-layout row wrap>
      <v-flex xs12 sm6>
        <UserDetail :ChildrenofUser="{name:name,familyName:'Park'}"></UserDetail> 
        <!--ChildrenofUser="{name:'Sally',familyName:'Jung'} 이나
        ChildrenofUser =1 과같이 객체나 숫자 형식도 ChildrenofUser에 담아 보낼수 있다. 
        객체형식으로 보냈을 경우. 자식컴포넌트에서 {{ChildrenofUser.name}}으로 표현  " -->
      </v-flex>
      <v-flex xs12 sm6>
        <UserEdit></UserEdit>
      </v-flex>
    </v-layout>
  </div>
</template>

<script>
import UserDetail from "./UserDetail.vue"
import UserEdit from "./UserEdit.vue"

export default {
  components: {
    UserDetail,
    UserEdit
  },
 data: () => ({
      name: 'Sky'
  }),
  methods:{
    nameChange(){
      this.name ='Sally'
    }
  }
}
</script>

2. UserDetail.vue - 자식 컴포넌트(객체 데이터 받아서 화면에 뿌림)

<template>
  <div class="red lighten-3 pa-3">
    <h3>More user Info</h3>
    <p>User Name</p>
    <p>{{ChildrenofUser.name}}</p> 
    <p>{{ChildrenofUser.familyName}}</p> 
  </div>
</template>
<script>


export default {
 props:{ChildrenofUser: Object},
 //props를 받을떄 객체나 숫자, 문자등 다양한 형태로 가져올 수 있기 때문에
 //어떤 타입인지 표시가 필요. 그러기 위해 props를 array형태가 아니라 
 //객체 형식으로 데이터이름과, 형식을 작성. 타입을 잘못쓰면 에러.
 data: () => ({
      ChildrenofUser: null
  })
}
</script>

Name Change를 클릭하면 부모컨포넌트와 자식컴포넌트의 데이터가 모두 변경됨.

 

728x90
반응형