언어/WEB

Vue - props 컴포넌트간 통신하기

앨리스.W 2023. 9. 28. 10:58

1.App.vue에 있는 데이터를 강제로 변경하는 건 불가능

//App.vue
<template>
  <section>
    <ul>
      <friend-contact 
        name ="aa"
        phone-number="111"
        email-address="@12"
        is-favorite="1"
      ></friend-contact>
      <friend-contact
        name ="bb"
        phone-number="222"
        email-address="@222"
        is-favorite="0"
      ></friend-contact>
    </ul>
  </section>
</template>
<!--FriendContact.vue-->
<template>
  <li>
    <h2>{{ name }}{{ isFavorite === '1' ? '()':''}}</h2>
    <button @click="toggleFavorite">Toggle Favorite</button>
    <button @click="toggleDetails">{{ detailsAreVisible ? 'Hide' : 'Show' }} Details</button>
    <ul v-if="detailsAreVisible">
      <li>
        <strong>Phone:</strong>
        {{ phoneNumber }}
      </li>
      <li>
        <strong>Email:</strong>
        {{ emailAddress }}
      </li>
    </ul>
  </li>
</template>

<script>
export default {
  //props 처리
  //특이한 점은 App.vue에는 - 로 이름을 적고 여긴 카멜방식으로 적음
  props:[
    'name',
    'phoneNumber',
    'emailAddress',
    'isFavorite'
  ],
  data() {
    return {
      detailsAreVisible: false,
    };
  },
  methods: {
    toggleDetails() {
      this.detailsAreVisible = !this.detailsAreVisible;
    },
    //App.vue에 있는 데이터는 변경은 오직 App.vue(부모)만 가능
    //이렇게 적으면 에러 발생
     toggleFavorite() {
       if(this.isFavorite === '1'){
         this.isFavorite = '0';
       }else {
         this.isFavorite = '1';
       }
     },

  }
};
</script>

1-1.변수를 지정해서 바꾸는 것

<!--FriendContact-->
<script>
export default {
  //props 처리
  //특이한 점은 App.vue에는 - 로 이름을 적고 여긴 카멜방식으로 적음
  props:[
    'name',
    'phoneNumber',
    'emailAddress',
    'isFavorite'
  ],
  data() {
    return {
      detailsAreVisible: false,
      friendIsFavorite:this.isFavorite, //변수 지정!!!!
    };
  },
  methods: {
    toggleDetails() {
      this.detailsAreVisible = !this.detailsAreVisible;
    },
    //App.vue에 있는 데이터는 변경은 오직 App.vue(부모)만 가능
    //변수를 지정해서 바꾸는 것
     toggleFavorite() {
       if(this.friendIsFavorite === '1'){
         this.friendIsFavorite = '0';
       }else {
         this.friendIsFavorite = '1';
       }
     },a

  }
};
</script>

1-2.부모 컴포넌트에 알리는 법

<!--FriendContact-->
<script>
export default {
  methods: {
    toggleFavorite() {
     // this.friendIsFavorite =!this.friendIsFavorite
     //부모 컴포넌트 수신 이벤트를 발생시켜줌, 두번째 인수는 이벤트와 함께 전달되는 데이터
     this.$emit('toggle-favorite',this.id); 
    },
  }
};
</script>

this.$emit를 통해 부모 컴포넌트에서 수신될 이벤트와 인수를 전달

<template>
  <section>
    <header>
      <h1>My Friends</h1>
    </header>
    <ul>
      <friend-contact 
      v-for="friend in friends"
      :key="friend.id"
      @toggle-favorite="toggleFavoriteStatus"
      ></friend-contact>
    </ul>
  </section>
</template>

<script>
export default {
  methods: {
    toggleFavoriteStatus(id) {
      const identifiedFriend = this.friends.find(friend => friend.id=id);
      identifiedFriend.isFavorite =!identifiedFriend.isFavorite;
    }
  }
};

자식 컴포넌트에서 toggle-favorite를 불렀고

그로 인해 부모 컴포넌트에서 toggle-favorite에 있는 이벤트가 실행됨

 

2.props안에 데이터 타입 등을 지정할 수 있음

<!--FriendContact-->
<script>
export default {
  //props 처리
  //특이한 점은 App.vue에는 - 로 이름을 적고 여긴 카멜방식으로 적음
  // props:[
  //   'name',
  //   'phoneNumber',
  //   'emailAddress',
  //   'isFavorite'
  // ],
  props:{
    name:{
      type:String,
      required: true
    },
    phoneNumber:{
      type:String,
      required: true
    },
    emailAddress: {
      type:String,
      required: true
    },
    isFavorite: {
      type:Boolean,
      required: false,
      default: false,
      // validator: function(value) {
      //   return value === '1' || value === '0';
      // }
    },
  },
};
</script>

3. v-for를 통해 컴포넌트를 반복해서 쓸 수 있다.

<template>
  <section>
    <header>
      <h1>My Friends</h1>
    </header>
    <ul>
      <friend-contact 
      v-for="friend in friends"
      :key="friend.id"
      :name="friend.name"
      :phone-number="friend.phone"
      :email-address="friend.email"
      :is-favorite="true"
      ></friend-contact>
    </ul>
  </section>
</template>

<script>
export default {
  data() {
    return {
      friends: [
        {
          id: "manuel",
          name: "Manuel Lorenz",
          phone: "0123 45678 90",
          email: "manuel@localhost.com",
        },
        {
          id: "julie",
          name: "Julie Jones",
          phone: "0987 654421 21",
          email: "julie@localhost.com",
        },
      ],
    };
  },
};
</script>

:를 통해 동적으로 사용 가능

 

반응형

'언어 > WEB' 카테고리의 다른 글

Vue - provide 와 inject  (0) 2023.09.30
Vue - $emit 쓰는 법  (0) 2023.09.29
Vue - 컴포넌트 사용법  (0) 2023.09.27
Vue - templete,$ref, 생명주기  (0) 2023.09.27
vue v-if,v-else,v-show  (0) 2023.09.17