inflearn logo
강의

講義

知識共有

Vue.js ちゃんと学んでみませんか(Vue.jsプロジェクト投入1週間前)

親コンポーネントで子コンポーネントのデータ値を同期する

안녕하세요.

327

kyungsookko01112547

投稿した質問数 3

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>
 
감사합니다.

vuex vuejs

回答 2

1

realprogrammers

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

0

mj Song

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

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

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

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

google login 를 따라하다가 오류 발생

0

937

1

Expected indentation of 2 spaces but found 4 오류

0

874

1

카카오 로그인 에러가 뜨세요

0

434

1

Multi-word질문드립니다.

0

234

2

설치 이후 npm run serve 화면 안나옴

0

651

1

vue cli 문제

0

361

2

요청드립니다.

0

160

0

eslint 에러발생

0

1384

1

main.js 질문드립니다.

0

228

1

vuex-persistedstate 는 동작 자체를 안하네요?

0

371

1

15강.조회화면 저장실습 - params안됨

0

286

1

array 넘겨주기

0

164

0

유튜브 4시간 강의와는 어떤 차이가 있을까요?

0

286

1

prefetch기능

0

738

1

테이블 list 랜더링 되지 않습니다.

0

254

1

펑션을 한 depth 더 들어가면 $호출이 안되는 이유가 뭘까요?

0

288

2

name 값이 없는 경우 오류

0

209

1

vue config 파일 문의

0

346

1

실무 레벨에서 공통코드(기준정보)는 어떻게 구현 할까요?

0

327

1

강의자료가 따로 있나요?

0

362

1

computed 대신 직접 this.$store.state.user 사용은 안되나요?

0

171

0

lazy-load의 성능에 대해서 질문이 있습니다.

0

205

0

Prefetch 관련 질문 드립니다.

0

143

1

저는 왜 하나의 단어가 지정이 안될까요?

0

313

1