부모컴포넌트에서 자식컴포넌트로 데이터를 내려주는 단방향 데이터 전달방식을 의미한다. 사용예제는 아래와 같다.
<template>
<div>{{title}}</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: '페이지 타이틀'
}
}
}
</script>
<template>
<div>
<PageTitle title="부모 컴포넌트에서 전송하는 페이지 타이틀" />
</div>
</template>
<script>
import PageTitle from '../components/child.vue'
export default {
name:'',
components: {PageTitle}
}
부모컴포넌트에서 직접 객체형태로 접근하는 방식으로는 ref를 사용하는 방법이 있다.
<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이벤트 명령
}
}
<template>
<div>
<button type="button" @click="childFunc" ref="child_btn">자식에 있는 클릭</button>
</div>
</template>
methods: {
childFunc() {
alert('부모 컴포넌트에서 직접 발생시킨 이벤트')
}
}
prop과는 반대로 자식컴포넌트에서 부모컴포넌트로 데이터를 전달하는 표현식을 의미한다. 사용예제는 아래와 같다.
<template>
<div>
<button type="button" @click="sendFromChild">자식 컴포넌트 버튼</button>
</div>
</template>
data() {
return {
msg: '자식 컴포넌트로 부터 보내는 메시지'
};
},
methods: {
sendFromChild() {
this.$emit('send-message', this.msg)
}
}
<template>
<div>
<Child @send-message="sendMessage" /> <!-- $emit의 이벤트명을 v-on:이벤트명 방식으로 템플릿에 구현 -->
</div>
</template>
import Child ~
components: {Child}
methods: {
sendMessage(data) {
alert(data)
}
}