Study/Vue
[Vue] 컴포넌트 통신 방식 Props, Event emit
JYHAN
2020. 12. 5. 22:33
Vue Component
뷰 컴포넌트는 고유한 데이터 유효 범위를 갖는다. 따라서 컴포넌트 간 데이터를 주고 받을 때는 아래 방식을 따른다.
상위 컴포넌트가 하위 컴포넌트로 데이터를 전송할 때는 props 로 전달한다
하위 컴포넌트가 상위 컴포넌트로 데이터를 전송할 때는 event 로 전달한다
Props
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<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>
var appHeader = {
template: '<h1>{{propsdata}}</h1>',
props: ['propsdata']
}
var appContent = {
template: '<h1>{{propsdata}}</h1>',
props: ['propsdata']
}
new Vue({
el: '#app',
components: {
'app-header': appHeader,
'app-content': appContent
},
data: {
message: 'hi hello',
num: 10
}
})
</script>
</body>
</html>
Emit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<app-header v-on:pass="logText"></app-header>
<app-content v-on:increase="increaseNum"></app-content>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var appHeader = {
// v-on:하위 컴포넌트에서 발생한 이벤트 이름="상위컴포넌트의 메서드 이름"
template: '<button v-on:click="passEvent">click me</button>',
methods:{
passEvent: function(){
this.$emit('pass');
}
}
}
var 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');
},
increaseNum: function(){
this.num += 1;
console.log(this.num);
}
},
data:{
num:10
}
})
</script>
</body>
</html>
www.inflearn.com/course/Age-of-Vuejs/
Vue.js 시작하기 - Age of Vue.js - 인프런
Vue.js로 쉽게 웹 개발할 수 있도록 기본 개념과 핵심 기능에 대해서 학습하고 구현해봅니다. 강좌를 들으시고 나면 Vue.js로 프런트엔드 개발을 하시는게 재밌어질거에요. 초급 웹 개발 프레임워
www.inflearn.com
joshua1988.github.io/vue-camp/
Cracking Vue.js
joshua1988.github.io
위 강좌를 통해 배운 내용을 정리했습니다.