Vue 컴포넌트 이해하기(1)

이선용·2022년 9월 16일
0

props

부모컴포넌트에서 자식컴포넌트로 데이터를 내려주는 단방향 데이터 전달방식을 의미한다. 사용예제는 아래와 같다.

child.vue

<template>
<div>{{title}}</div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: '페이지 타이틀'
    }
  }
}
</script>

mother.vue

<template>
<div>
  <PageTitle title="부모 컴포넌트에서 전송하는 페이지 타이틀" />
</div>
</template>

<script>
import PageTitle from '../components/child.vue'
export default {
  name:'',
  components: {PageTitle}
}

부모컴포넌트에서 직접 객체형태로 접근하는 방식으로는 ref를 사용하는 방법이 있다.

MotherComponent.vue

<template>
<div>
  <button type="button" @click="callChildFunc">부모에 있는 클릭</button>
  <ChildComponent ref="child_components" />
</div>
</template>

import ChildComponent from './ChildComponent.vue'
components: {ChildComponent},
methods: {
    callChildFunc() {
      this.$refs.child_component.childFunc(); //ChildComponent에 접근한 후 click이벤트 명령
    }
  }

ChildComponent.vue

<template>
<div>
  <button type="button" @click="childFunc" ref="child_btn">자식에 있는 클릭</button>
</div>
</template>

methods: {
  childFunc() {
    alert('부모 컴포넌트에서 직접 발생시킨 이벤트')
  }
}

$emit

prop과는 반대로 자식컴포넌트에서 부모컴포넌트로 데이터를 전달하는 표현식을 의미한다. 사용예제는 아래와 같다.

child.vue

<template>
<div>
  <button type="button" @click="sendFromChild">자식 컴포넌트 버튼</button>
</div>
</template>

data() {
    return {
      msg: '자식 컴포넌트로 부터 보내는 메시지'
    };
},
methods: {
   sendFromChild() {
      this.$emit('send-message', this.msg)
    }
}

parent.vue

<template>
<div>
  <Child @send-message="sendMessage" /> <!-- $emit의 이벤트명을 v-on:이벤트명 방식으로 템플릿에 구현 -->
</div>
</template>
import Child ~
components: {Child}
methods: {
    sendMessage(data) {
      alert(data)
    }
}
profile
React, Vue등 여러 라이브러리와 프레임워크를 배우고 활용하기를 좋아하는 주니어 프론트엔드 개발자 입니다. 저에게 흥미가 있거나 궁금한점이 있으신 분들은 글을 남겨주시면 언제든지 응답해드리겠습니다.

0개의 댓글