뷰 컴포넌트는 각각 고유한 데이터 유효범위를 갖습니다.
따라서, 컴포넌트 간에 데이터를 주고 받기 위해선 아래와 같은 규칙을 따라야 합니다.
<div id="app">
<!-- <app-header v-bind:프롭스 속성 이름 ="상위 컴포넌트의 데이터 이름"></app-header> -->
<app-header v-bind:propsdata ="message"></app-header>
<app-content v-bind:propsdata ="num"></app-content>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// {{ }} 데이터바인딩 문법
const appHedaer = {
template: '<h1>{{ propsdata }}</h1>',
props: ['propsdata']
}
const appContent = {
template: '<div>{{ propsdata }}</div>',
props: ['propsdata']
}
new Vue({
el: '#app',
components: {
'app-header': appHedaer,
'app-content': appContent
},
data: {
message: 'hi',
num: 10
}
})
</script>
Root
의 데이터객체 message: 'hi', num: 10
appHeader
에서 입력한 상위 데이터를 propsdata
로 출력 ('hi')
<app-header v-bind:propsdata ="message"></app-header>
appContent
에서 입력한 상위 데이터를 propsdata
로 출력 (10)
<app-content v-bind:propsdata ="num"></app-content>
<div id="app">
<!-- <app-header v-on:하위 컴포넌트에서 발생한 이벤트 이름="상위 컴포넌트의 메서드 이름"></app-header> -->
<app-header v-on:pass="logText"></app-header>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const appHeader = {
template : '<button v-on:click="passEvent">click me</button>',
methods: {
passEvent: function() {
this.$emit('pass');
}
}
}
new Vue({
el: '#app',
components: {
'app-header': appHeader
},
methods: {
logText: function(){
console.log('hi');
}
}
})
</script>
<div id="app">
<p>{{ num }}</p>
<!-- <app-header v-on:하위 컴포넌트에서 발생한 이벤트 이름="상위 컴포넌트의 메서드 이름"></app-header> -->
<app-header v-on:pass="logText"></app-header>
<app-content v-on:increase="increaseNumber"></app-content>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const appHeader = {
template : '<button v-on:click="passEvent">click me</button>',
methods: {
passEvent: function() {
this.$emit('pass');
}
}
}
const appContent= {
template: '<button v-on:click="addNumber">add</button>',
methods: {
addNumber: function() {
this.$emit('increase');
}
}
}
new Vue({
el: '#app',
components: {
'app-header': appHeader,
'app-content': appContent
},
methods: {
logText: function(){
console.log('hi');
},
increaseNumber: function() {
this.num = this.num + 1;
}
},
data: {
num: 10
}
})
</script>
하위컴포넌트 increase 이벤트가 상위컴포넌트 increaseNumber로 이벤트를 올려줌
상위컴포넌트의 data의 값이 변하는 이벤트를 적용.
하위컴포넌트 increase 이벤트 this.$emit('increase');