상위(부모) 컴포넌트가 하위(자식) 컴포넌트를 호출하여 사용가능 함
<script>
import ChildComp from './ChildComp.vue'
export default {
components: { // 자식 컴포넌트 선언
ChildComp
}
}
</script>
<template>
<ChildComp /> <!--자식 컴포넌트 호출 할때-->
</template>
<template>
<h2>자식 컴포넌트가 호출되면 이게 나와요</h2>
</template>
<script>
watch: {
locale(newlocale) {
localStorage.setItem('locale', newlocale);
},
}
</script>
<template>
<select class="form-select" v-model="locale">
<option>ko</option>
<option>en</option>
</select>
</template>
부모 컴포넌트는 자식 컴포넌트에 props를 통해 데이터 전달 가능
<script>
import ChildComp from './ChildComp.vue'
export default {
components: {
ChildComp
},
data() {
return {
greeting: '부모 컴포넌트로부터 전달받았어요!'
}
}
}
</script>
<template>
<ChildComp :msg="greeting" />
</template>
<script>
export default {
props: {
msg: String
}
}
</script>
<template>
<h2>{{ msg || 'prop이 아직 전달되지 않았습니다!' }}</h2>
</template>
자식 컴포넌트가 부모 컴포넌트한테 emit를 통해 데이터 전달 가능
<script>
import ChildComp from './ChildComp.vue'
export default {
components: {
ChildComp
},
data() {
return {
childMsg: '자식 컴포넌트로부터 아직 메시지를 받지 못했어요!'
}
}
}
</script>
<template>
<ChildComp @response="(msg) => childMsg = msg" />
<p>{{ childMsg }}</p>
</template>
<script>
export default {
emits: ['response'],
created() {
this.$emit('response', '자식 컴포넌트로부터 emit를 받았어요!')
}
}
</script>
<template>
<h2>자식 컴포넌트</h2>
</template>