Vue.js 컴포넌트 간 데이터 전달
상위 컴포넌트 -> 하위 컴포넌트
하위 컴포넌트 ( ChildComponent.vue )
props에 상위 컴포넌트로부터 전달 받을 데이터의 속성을 정의한다.
<template>
<div>
{{ this.data }}
</div>
</template>
<script>
export default {
name: "ChildComponent",
props: {
data: String,
},
};
</script>
<style scoped></style>
상위 컴포넌트 ( ParentComponent.vue )
하위 컴포넌트 tag 안에서 "v-bind:(props 이름)" 속성을 정의하여 데이터를 바인딩 한다.
"v-bind" 키워드는 생략할 수 있다.
<template>
<div>
<ChildComponent v-bind:data="value"></ChildComponent>
<ChildComponent :data="value"></ChildComponent>
</div>
</template>
<script>
export default {
name: "ParentComponent",
data() {
return {
value: "Hello World",
};
},
};
</script>
<style scoped>
</style>
하위 컴포넌트 -> 상위 컴포넌트
하위 컴포넌트 ( ChildComponent.vue )
하위 컴포넌트에서 이벤트가 발생했을 때 상위 컴포넌트에서 호출할 메서드명을 받을 속성을 this.$emit() 에 정의한다.
this.$emit("속성명"[, 파라미터1, 파라미터2, ...])
<template>
<div>
<button @click="click">클릭</button>
</div>
</template>
<script>
export default {
name: "ChildComponent",
methods: {
search(e) {
this.$emit("searchEvent", e);
},
},
};
</script>
<style scoped></style>
상위 컴포넌트 ( ParentComponent.vue )
하위 컴포넌트 tag 안에서 "v-on:(emit()에서 정의한 속성명)" 속성에 메서드명을 전달한다.
<template>
<div>
<ChildComponent v-on:clickEvent="click"></ChildComponent>
</div>
</template>
<script>
export default {
name: "ParentComponent",
methods: {
click() {
console.log("click...");
},
},
};
</script>
<style scoped>
</style>'Advance II > Vue.js' 카테고리의 다른 글
| Vuetify 설치 및 개발 환경 구성 (0) | 2023.09.25 |
|---|---|
| vue.js 입문 (0) | 2023.03.01 |