[Vue.js] 컴포넌트 심화2
부모 컴포넌트에서 자식 컴포넌트의 이벤트 직접 발생시키기
부모 컴포넌트에서 자식 컴포넌트의 버튼을 클릭하는 이벤트를 만들어보자
ChildComponent.vue
<template>
<button type="button" @click="childFunc" ref="btn">click</button>
</template>
<script>
export default{
methods:{
childFunc(){
console.log('부모 컴포넌트에서 직접 발생시킨 이벤트');
}
}
}
</script>
위처럼 자식 컴포넌트 생성. ref=’btn’ 으로 접근할 수 있도록 작성했다.
HTML 태그에 ref=’id’를 지정하면 Vue 컴포넌트의 함수에서 this.$refs를 통해 접근이 가능하게 된다. ref 속성은 HTML 태그에서 사용되는 id와 비슷한 기능을 한다고 생각하면 된다. ref는 유일한 키 값을 사용해야 한다.
ParentComponent.vue
<template>
<child-component @send-message="sendMessage" ref="child-component" />
</template>
<script>
import ChildComponent from './ChildComponent';
export default{
components:{ChildComponent},
mounted() {
this.$refs.child_component.$refs.btn.click()
}
}
</script>
부모 컴포넌트에서 자식 컴포넌트인 child-component에 ref=’child_component’를 지정해서 $refs로 접근할 수 있도록 했다.
이렇게 하면 부모 컴포넌트의 버튼을 클릭하여 자식 컴포넌트의 버튼 클릭 이벤트를 실행 => consol.log가 실행된다.
부모 컴포넌트에서 자식 컴포넌트의 함수 직접 호출하기
ChildComponent2
<template>
<div></div>
</template>
<script>
export default{
methods:{
callFromParent(){
console.log('부모 컴포넌트에서 직접 호출한 함수')
}
}
}
</script>
ParentComponent2
<template>
<child-component @send-message="sendMessage" ref="child_component" />
</template>
<script>
import ChildComponent from './ChildComponent2';
export default{
components:{ChildComponent},
mounted() {
this.$refs.child_component.callFromParent();
}
}
</script>
부모 컴포넌트에서는 자식 컴포넌트를 $refs를 사용하여 접근하게 되면 자식 컴포넌트 내에 정의된 모든 함수를 호출할 수 있다.
부모 컴포넌트에서 자식 컴포넌트의 데이터 옵션 값 직접 변경하기
<template>
<h1>{{ msg }}</h1>
</template>
<script>
export default{
data(){
return{
msg : '야호~'
};
}
}
</script>
ChildComponent3에서 위처럼 msg에 특정 문구를 담아주고
ParentComponent3에서
<template>
<child-component ref="child_component" />
<button type = "button" @click="changeChildData">change Child Data</button>
</template>
<script>
import ChildComponent from './ChildComponent3';
export default{
components:{ChildComponent},
methods:{
changeChildData(){
this.$refs.child_component.msg = "부모 컴포넌트가 변경한 데이터"
}
}
}
</script>
위 화면에서 처음 로딩되는 화면에는 위에서 담았던 msg : '야호~'
라는 화면으로 나오지만
<button type = "button" @click="changeChildData">change Child Data</button>
버튼을 누르게 되면
이 버튼에 연결된 함수가 msg에 정의된 데이터를 바꾼다.
자식 컴포넌트에서 부모 컴포넌트로 이벤트/데이터 전달하기(커스텀 이벤트)
자식 컴포넌트에서 부모 컴포넌트로 이벤트를 전달하기 위해서는 $emit을 사용한다.
ChildComponent4
<template>
<div></div>
</template>
<script>
export default{
data(){
return{
msg: '자식 컴포넌트로부터 보내는 메시지'
};
},
mounted() {
this.$emit('send-message', this.msg)
}
}
</script>
자식 컴포넌트가 mounted 되면 $emit을 통해 부모 컴포넌트의 send-message 이벤트를 호출한다. 이때 msg 데이터를 파라미터로 전송한다.
ParentComponent4
<template>
<child-component @send-message = "sendMessage" />
</template>
<script>
import ChildComponent from './ChildComponent4'
export default{
components:{ChildComponent},
methods:{
sendMessage(data) {
console.log(data);
}
}
}
</script>
부모 컴포넌트에서 자식 컴포넌트인 ChildComponent를 import 하고, 커스텀 이벤트(@send-message)를 정의한다. 커스텀 이벤트인 send-message는 자식 컴포넌트에서 $emit으로 호출하게 된다. 이때 부모 컴포넌트에 정의된 sendMessage 함수가 실행되고, 자식 컴포넌트로부터 전달받은 데이터를 부모 컴포넌트에서 사용할 수 있다.
부모 컴포넌트에서 자식 컴포넌트의 데이터 옵션 값 동기화하기
부모 컴포넌트에서 computed를 이용하면 자식 컴포넌트에 정의된 데이터 옵션값의 변경 사항을 항상 동기화시킬 수 있다.
ChildComponent5.vue
<template>
<button type="button" @click="childFunc" ref="btn">자식 컴포넌트 데이터 변경</button>
</template>
<script>
export default{
data(){
return{
msg: "메시지"
};
},
methods:{
childFunc(){
this.msg = "변경된 메시지";
}
}
}
</script>
기본적으로 msg 변수 안에 “메시지”라고 값을 정의해준다. 그리고 버튼을 클릭하면 메시지라고 저장된 변수의 값이 변경된 메시지로 바뀌는 메소드도 생성해준다.
ParentComponent5.vue
<template>
<button type="button" @click="checkChild">자식 컴포넌트 데이터 조회</button><br>
<child-component ref = "child_component" />
</template>
<script>
import ChildComponent from './ChildComponent5'
export default{
components:{ChildComponent},
computed:{
msg(){
return this.$refs.child_component.msg;
}
},
methods:{
checkChild(){
alert(this.msg)
}
}
}
</script>
그리고 부모 컴포넌트에서 자식 컴포넌트의 데이터를 조회하는 버튼 하나, 자식 컴포넌트를 그대로 삽입해주는 버튼 하나, 2개를 만들어주고 위의 자식 컴포넌트 데이터 조회 버튼을 클릭하면 자식 컴포넌트의 data()에서 정의된 msg “메시지”가 출력되고 자식 컴포넌트의 버튼을 클릭한다면 자식 컴포넌트의 값이 변경되어 출력된다.
부모 컴포넌트에서는 computed 옵션을 사용해서 자식 컴포넌트의 msg 값을 감지하도록 했다. computed는 참조되고 있는 데이터의 변경사항을 바로 감지하여 반영할 수 있다.
computed 옵션을 이용하면 자식 컴포넌트의 데이터가 변경될 때마다 $emit를 통해 변경된 데이터를 전송하지 않아도 변경된 데이터 값을 항상 확인할 수 있다.
댓글남기기