• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

안녕하세요.

21.12.28 21:47 작성 조회수 180

0

안녕하세요. 데이터를 동기화 할때 부모 컴포넌트에서 computed에 있는 메서드 명을 html 템플릿에 값으로 넣으니 에러가 나서 질문 드립니다.
 
제 생각에는 html 태그에 자식으로 부터 computed를 통해 가져오는 msg값이 초기 랜더링때 없어서 문제가 발생 하는거 같습니다.. 해당 msg를 보여주는 html템플릿을 주석 처리하면 정상적으로 랜더링 하고 해당 부분을 다시 주석을 해제하면 핫리로드를 통해 정상 작동하더라고요.
 
return this.$refs?.child_component?.msg || ''; 나 템플릿에 {{ msg || ''}}를 해도 해결이 안되는데 이때는 어떻게 해야할까요?
 
제가 원하는건 자식에 있는 값을 바꾸면 부모도 감지하고 바로 바뀌는 것을 원합니다.
 
<template lang="">
<div>
<h1>Parents Component</h1>
<button @click="onParentsClick">상위 엘리먼트</button>
<ChildComponent ref="child_component" @send-msg="sendMsg"/>
<p>{{msg || ''}}</p>
</div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
components: {
ChildComponent
},
computed: {
msg() {
return this.$refs?.child_component?.msg || '';
}
},
methods: {
onParentsClick() {
console.log(this.msg);
this.$refs.child_component.$refs.child_btn.click();
this.$refs.child_component.childMethod();
this.$refs.child_component.msg = 'parents msg';
console.log(this.$refs.child_component);
},
sendMsg(text) {
console.log(text)
}
}
}
</script>

<style lang="">
 
</style>
 
<template>
<div>
<h2>Child Component</h2>
<button @click="onChildClick" ref="child_btn">하위 엘리먼트</button>
<p>{{msg}}</p>
<button @click="sendChild">자식 컴포넌트</button>
<button @click="changeData">부모 정보 동기화</button>
</div>
</template>
<script>
export default {
name: '',
data() {
return {
msg: 'children msg'
}
},
methods: {
onChildClick() {
console.log('this is child component');
this.msg = 'children msg'
},
childMethod() {
console.log('this is child method')
},
sendChild() {
this.$emit('send-msg', this.msg)
},
changeData() {
this.msg = 'from children to parents';
}
},
}
</script>
<style>
 
</style>
 
감사합니다.

답변 2

·

답변을 작성해보세요.

1

이럴경우 computed로 하는 것 보다 자식 컴포넌트에서 변경감지 하려는 데이터 값을 watch로 감시하고 변경이 일어나면 부모 컴포넌트로 this.$emit으로 이벤트 발생시키고 변경된 값을 전달해야 합니다.

0

mj Song님의 프로필

mj Song

2022.02.06

방법 공유합니다.
문제는 말씀하시는 것처럼 렌더링 시에 msg를 참조해야 하는데 refs에 child라는 값이 없어서 그렇습니다.

그렇기에 옵셔널 체이닝을 사용하시면 방지가 됩니다.

this.$refs.child?.msg || '대체 문자'

옵셔널 체이닝이란? - 참고